Python 程序未将字符串与文本文件中的单词匹配
我有以下Python程序。它的目的是通过对照所附字典(words.txt)检查单词并输出正确的单词来自动解读Caesar密码 但是,尽管我可以看到行是相同的(例如,我可以通过调试看到字符串是“hello”,文本文件中的行是“hello”,但它显示为未找到匹配项。我已删除了换行符,但我假设文本文件中还有其他不可见的内容导致了问题 文本文件的格式是一行中的每个单词。问题似乎在于Python 程序未将字符串与文本文件中的单词匹配,python,Python,我有以下Python程序。它的目的是通过对照所附字典(words.txt)检查单词并输出正确的单词来自动解读Caesar密码 但是,尽管我可以看到行是相同的(例如,我可以通过调试看到字符串是“hello”,文本文件中的行是“hello”,但它显示为未找到匹配项。我已删除了换行符,但我假设文本文件中还有其他不可见的内容导致了问题 文本文件的格式是一行中的每个单词。问题似乎在于 if line == possibilities[i][j]: 但我似乎不知道问题出在哪里 import string
if line == possibilities[i][j]:
但我似乎不知道问题出在哪里
import string
words = []
possibilities = [[]*1 for i in range(26)]
possStrings = []
startPos = -1
nextPos = 0
temp = []
count = 0
uppers = []
print("Please enter your scrambled text")
crypt = str(input())
crypt = crypt.translate(str.maketrans('', '', string.punctuation))
for i in range(len(crypt)):
if crypt[i].isupper():
uppers.append(True)
else:
uppers.append(False)
if (i > 1 and crypt[i] == " ") or (i == len(crypt)-1):
if (i == len(crypt)-1):
nextPos = i+1
else:
nextPos = i
words.append(crypt[startPos+1:nextPos])
startPos = i
for i in range(26):
for word in words:
for j in range(len(word)):
a = ord(word[j])
a += i
if a > 122:
a -= 26
temp.append(chr(a))
possibilities[i].append(''.join(temp))
temp = []
count += 1
probability = [0]*25
with open("words.txt", "r") as dictionary:
for i in range(25):
for j in range(len(words)):
for line in dictionary:
line = line.strip('\n')
if line == possibilities[i][j]:
probability[i] += 1
if probability[i] == len(words):
break
print(probability)
winner = probability.index(max(probability))
if winner == 0:
print("No match was found for this sentence")
else:
print("The closest match to this sentence is", '"'+' '.join(possibilities[winner])+'"')
您的代码可以很好地进行以下更改: 1_uu查找文件处理程序“dictionary”(您可能希望在此处使用更好的名称以减少混淆),使用以下方法返回到
words.txt
文件的开头:
dictionary.seek(0)
在第50行(在文件行中的循环之后)
2.index
方法如果找不到匹配项,将引发ValueError。(请阅读类似以下内容的帮助:python3-c“help([].index)”
)。因此,您可以执行以下操作:
try:
if max(probability) > 0:
winner = probability.index(max(probability))
print("The closest match to this sentence is", '"'+' '.join(possibilities[winner])+'"')
else:
raise ValueError
except ValueError:
print("No match was found for this sentence")
现在进行更改:
> Please enter your scrambled text
gdkkn zcdqbgnw
The closest match to this
sentence is "hello aderchox"
完整的工作代码:
- 同样在第13行,您不需要使用
,因为input()本身会给您一个字符串(尽管这没有任何区别)str()
- 如果行==可能性[i][j]:,则行
没有问题。您只需使用
进行尝试即可python3-c“print”(“test”==“test”)”
此外,与第17行到第28行之间的for循环不同,您可以在输入句子中获得小写单词列表,其一行代码如下所示:
words = list(map(str.lower,crypt.split()))
嗯