Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何编写pyhton代码,在不包含字母表中每个字母的文件中打印单词数?_Python_Python 3.x - Fatal编程技术网

Python 如何编写pyhton代码,在不包含字母表中每个字母的文件中打印单词数?

Python 如何编写pyhton代码,在不包含字母表中每个字母的文件中打印单词数?,python,python-3.x,Python,Python 3.x,我一直在尝试编写Python3代码来计算文件中不包含字母表中每个字母的字数,但循环似乎只对第一个字母“a”起作用。虫子在哪里 fin = open('words.txt') def avoids (word, string): for i in string: for l in word: if l == i: return False return True alphabet = 'abcdefghijkl

我一直在尝试编写Python3代码来计算文件中不包含字母表中每个字母的字数,但循环似乎只对第一个字母“a”起作用。虫子在哪里

fin = open('words.txt')
def avoids (word, string):
    for i in string:
        for l in word:
            if l == i:
                return False
    return True
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for f in alphabet:
    n = 0
    for line in fin:
        word = line.strip()
        if (avoids (word, f)):
            n += 1
    print (f, n)
“words.txt”文件可通过以下链接下载:

输出如下所示:

a 57196
b 0
c 0
d 0
e 0
f 0
g 0
h 0
i 0
j 0
k 0
l 0
m 0
n 0
o 0
p 0
q 0
r 0
s 0
t 0
u 0
v 0
w 0
x 0
y 0
z 0

您需要在打开文件后读取该文件,然后拆分以获取文本作为单词列表。然后,您可以在单词和字母表上循环:

import string
with open('words.txt', 'r') as f:
    text = f.read()

words = text.split()
for letter in string.ascii_lowercase:
    print(letter, len([w for w in words if letter not in w]))

您的问题是,第一次运行循环时,您到达了文件的末尾,要在开始时重新启动,请添加以下行:

fin.seek(0)

在字母循环中,就像重置n=0一样

我认为问题不在于读取文件,因为循环在第一次强制转换时运行良好,并返回不包含字母“a”的字数。我还尝试了以下代码,似乎正在运行:
fin=open('words.txt')for line in fin:word=line.strip()if(len(word)>20):print(word)
它打印长度大于20的单词characters@SimonR-您可以使用内置的
string
库的
ascii\u lowercase
属性,而不是声明整个字母表。@S3DEV。美好的我不知道那件事。我更新了我的答案,将其纳入其中。谢谢@SimonR您的输出也不包括“a”的字数@SimonR我只需要知道我的代码提示中的错误在哪里:您可以使用内置
字符串
库的
ascii_lowercase
属性,而不是声明整个字母表。
避免()
功能。不理想。我建议找一个更好的方法。此外,请记住关闭文本文件,或者更好地使用
with
idiom.WOW!作品很有魅力,非常感谢@Mariana Blaz,我真的从你那里学到了很多。