私は、入力された文章を取って、各単語と句読点の位置を辞書に入れて、その文章を次のように正確に再現します元は、私はプログラムを取得することはできませんコンマを置く辞書と辞書の位置。ただし、他のすべての句読点でも機能します。これは私のコードは助けてください!Python - 辞書に書き込むコンマを得ることができません
def calPositions():
import json #imports the json module
import re #imports the regular expression module
from collections import defaultdict #imports a dictionary
punctuation = r"[ {},:'[\]1-5]+"
d = defaultdict(list) #creates the dictionary and assigns it too the variable d
sentence = input("Please enter a sentence: ") #Asks the user to input a sentence
for position, word in enumerate(re.split(punctuation, sentence), start=1):# goes through each word one by one
d[word].append(position) #gives each word in the sentence a position
print ("your sentence was: " ,sentence) #displays the sentence the user entered
print ("The sentence with their positions of the words is: ",d) #displays the position of the words
json.dump(d, open("original.txt",'w')) #puts the dictionary in the file
menu() #sends the user back to the menu
def recreate():
import json
d = json.load(open("original.txt")) #opens the text file so it can be read
print (d) #displays the dictionary
position = 1 #creates the variable position
sentence2 = []
while position:
for word, positions in d.items():# this uses the positions of the words
if position in positions: # to put the words in the correct order
sentence2.append(word) # so the recreated sentence can be displayed
position += 1
break
else:
position = 0
print(' '.join(sentence2))#prints the recreated sentence
menu()
def menu():
correct = "false"
while correct == "false":
print("""
Welcome to the program. Please choose an option.""")#displays the options for the user
choice =input("""
Option 1 Input sentence to calculate positions - calculate
Option 2 Recreate orginal sentence - recreate
Option 3 End - end : """)
if choice == "calculate":
correct = "true"
calPositions() # if the user chooses calculate it runs the function calPositions
elif choice == "recreate":
correct = "true"
recreate() # if the user chooses recreate it runs the function recreate
elif choice == "end":
correct = "true"
return # if the user chooses end the program ends
else:
print("Please enter a valid option.")#if the user inputs anything else it asks them to enter a valid option
メニュー()
入力/出力/予想出力を表示できますか? –
インデントの問題を修正し、入出力を共有してください。 –
これは、重複する単語で動作します。これは、文章中に現れる位置の両方の位置を与えます。このコードでは機能しない唯一のものは、カンマで文章を入力し、カンマをカンマで辞書に入れないプログラムです。ポジション –