繁体   English   中英

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

[英]Efficient python for loop using txt files

因此,我正在研究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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM