使用txt文件的高效python for循环

时间:2018-08-28 17:52:57

标签: python performance 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

有什么提示吗?

1 个答案:

答案 0 :(得分:0)

这是一种可以处理任意长度单词的文本输入的解决方案:

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)