我正在尝试进行比较,以查看列表中的单词是否在字典中或字词中。我正在编写一个解码txt文件的程序。
这里说的是一行:
['Now', 'we', 'are', 'engaged', 'in', 'a', 'great', 'civil', 'war,']
我想去字典并查看是否有任何这些单词。如果是这样,我会将字符串放在一起并写入文件。我想知道的是如何比较两者。我首先小写列表中的第一个单词,因为所有单词都是小写的。
我的字典的例子是:
{"now": "", "help": "", "you": ""}
但是还有更多的话。
如果你想查看我的整体代码,请问:)
这是我制作字典的代码。每一行都是一个单词。
f = open('dictionary.txt', "r")
dictionary = {}
for line in f:
word = line.strip()
dictionary[word] = ""
print dictionary
更新
def CaeserCipher(string, k):
#setting up variables to move through
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'*10000
lower = 'abcdefghijklmnopqrstuvwxyz'*10000
newCipher = ''
#looping each letter and moving it k times
for letter in string:
if letter in upper:
if upper.index(letter) + k > 25:
indexPosition = (upper.index(letter) + k)
newCipher = newCipher + upper[indexPosition]
else:
indexPosition = upper.index(letter) + k
newCipher = newCipher + upper[indexPosition]
elif letter in lower:
if lower.index(letter) + k > 25:
indexPosition = (lower.index(letter) + k)
newCipher = newCipher + lower[indexPosition]
else:
indexPosition = lower.index(letter) + k
newCipher = newCipher + lower[indexPosition]
else:
newCipher = newCipher + letter
return newCipher
f = open('dictionary.txt', "r")
dictionary = set()
for line in f:
word = line.strip()
dictionary.add(word)
print dictionary
#main file
#reading file and encrypting text
f = open('encrypted.txt')
string = ''
out = open("plain1.txt", "w")
#working through each line
for line in f:
for k in range(26):
line = [CaeserCipher(word, k) for word in line]
print line
#listSplit = re.split('[,\[\]]', line)
#print listSplit
string = ("".join(line))
listOfWords = string.split()
lowercase_line = [word.lower() for word in listOfWords]
out.write(dictionary.intersection(lowercase_line))
f.close()
out.close()
答案 0 :(得分:3)
如果您愿意将字典表示为一个集合,则可以使用intersection
查找字典中存在的所有单词。
dictionary = {"now", "help", "you"}
line = ['Now', 'we', 'are', 'engaged', 'in', 'a', 'great', 'civil', 'war,']
lowercase_line = [word.lower() for word in line]
#todo: also filter out punctuation, so "war," becomes "war"
print dictionary.intersection(lowercase_line)
结果:
set(['now'])
答案 1 :(得分:0)
if any(word.lower() in your_word_dict for word in line_list):
' '.join(line_list)
# write to file
检查单词列表中的任何单词是否在您的词典中,以及是否将它们加入字符串并将其写入文件