使用 txt 文件的高效 python for loop



所以,我正在做一个python项目(我是初学者(,但是我在将列表与文本文件中的单词进行比较时遇到了问题。这是一个应该解密单词的程序。

your_chars = input("Input characters:")
complete_list = []
final_lst = []
for current in range(len(your_chars)):
a = [i for i in your_chars]
for y in range(current):
a = [x + i for i in your_chars for x in a]
complete_list = complete_list+a
with open("P:/words.txt", "r") as file:
for i in complete_list
for x in file:
final_lst.append(x)
print(final_lst)

我认为它应该可以工作,但显然它不是很有效(尤其是最后三行(,但我想不出另一种写法。

前任:

输入:yhe

输出:hey

有什么提示吗?

下面是一个可以处理具有任意长度单词的文本输入的解决方案:

from collections import Counter
your_text = input('input characters')
with open('P:/words.txt', 'r') as infile:
file_text = infile.read()
old_words = {
str(sorted(Counter(w).items())): w
for w in file_text.split()
}
for w in your_text.split():
i = str(sorted(Counter(w).items()))
if i in old_words:
print(old_words[i])

它不需要检查输入字符的每个排列;当输入单词中的字母计数与输入文件中的字母计数相同时,它会匹配。


这是我的第一个解决方案并且有效,但不要输入单词长度超过 10 个字符的字符串,否则会使您的计算机崩溃:

from itertools import permutations
perms_list = []
perms = []
matches = []
your_chars = input("input characters")
your_words = your_chars.split()
for word in your_words:
perms_list.append([i for i in permutations(word)])
for word in perms_list:
for perm in word:
perms.append(''.join(list(perm)))
with open('P:/words.txt', 'r') as comparefile:
file_contents = comparefile.read().split()
for permutation in perms:
if permutation in file_contents:
matches.append(permutation)
print(matches)

最新更新