我正在尝试制作一个程序,该程序使用用户的单词,对其进行更改,然后吐出更改后的单词。目前,我正在使用输入,并使用.split(“”)分割输入。该程序适用于单数单词,但是只要您有类似“我的兄弟放开派对”之类的短语,就会出现此错误:
my dude lets go party
['my', 'dude', 'lets', 'go', 'party']
In: my
my word: my dude lets go party
my word my dude lets go party
Traceback (most recent call last):
File "<ipython-input-62-3118b5db1cd0>", line 1, in <module>
runfile('/home/jack/Desktop/PythonProjects/code/dogsbody.py', wdir='/home/jack/Desktop/PythonProjects/code')
File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/jack/Desktop/PythonProjects/code/dogsbody.py", line 48, in <module>
print(wordSelector(fword=userInput))
File "/home/jack/Desktop/PythonProjects/code/dogsbody.py", line 30, in wordSelector
possibilities = Word(fword).synsets[0].lemma_names()
IndexError: list index out of range
这似乎是因为我的for循环没有意识到我将句子拆分成单独的部分,这很奇怪,因为当您打印拆分后的句子时,它会将项目分开。
from textblob import Word
def wordScore(fword):
ref = {'e': 1, 't' : 2, 'a' : 3, 'o' : 4, 'i' : 5, 'n' : 6, 's' : 7, 'r': 8, 'h' : 9, 'l' : 10, 'd' : 11, 'c' : 12,
'u': 13, 'm': 14, 'f': 15, 'p': 16, 'g': 17, 'w': 18, 'y': 19, 'b': 20, 'v': 21, 'k': 22, 'x': 23,
'j': 24, 'q': 25, 'z': 26, "'": -10, '-': 30}
score = 0
for letter in fword:
score += ref[letter]
return score
def wordSelector(fword):
print("my word: " + fword)
bestReplacement = ""
bestScore = 1000
if(fword == " "):
return " "
print("my word " + fword)
possibilities = Word(fword).synsets[0].lemma_names()
for possibility in possibilities:
tempScore = wordScore(fword=possibility)
if(tempScore < bestScore):
bestReplacement = possibility
bestScore = tempScore
return bestReplacement
userInput = input()
userWords = userInput.split(" ")
print(userWords)
for word in userWords:
print("In: " + word)
print(wordSelector(fword=userInput))