繁体   English   中英

来自文本文件的Python字长计数

[英]Python word length count from a text file

我正在做一个项目。 我已经能够完成所有要求的事情,包括总行数,分隔和排序以及总字母数。 我遇到的问题是列出每个单词的长度。 示例:the:3,it:2,等等...我不是要查找它出现在文本文件中的次数。

i=open("words.txt").read().splitlines()

f= len(open("words.txt").readlines())

t= sorted (i)

e= "\n".join(t)

g= sum(len(e) for e in (i))

非常感谢任何关于如何为每个单词设置单词长度的帮助。

这应该是您要寻找的:

string = open('file.txt').read()

for word in string.split():
    print len(word)

假设每行有许多单词,并用空格分开。

with open('words.txt') as my_file:
    words = []
    for line in my_file:
        words.extend(line.split())
print {w: len(w) for w in words)}

或者:

with open('words.txt') as my_file:
    print {w: len(w) for w in words.split() for words in line for line in my_file}

不确定是否是最佳选择,但是如果每个单词都用空格分隔,则应该可以使用:

i=open("words.txt").read().splitlines()

[[len(k) for k in j.split(' ')] for j in i]

你可以这样做:

>>> with open('/usr/share/dict/words','r') as f:
...    print(max(f,key=len))
... 
formaldehydesulphoxylate

然后,取其长度:

>>> with open('/usr/share/dict/words','r') as f:
...    longest=max(f,key=len)
... 
>>> print(len(longest))
25

暂无
暂无

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

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