python-3.x - 文本文件中每行的总字数
问题描述
我想计算文本文件每行中的单词数(不包括第一个单词),然后打印其中单词最多的行的第一个单词?
目前我只能计算整个文本文件中的单词数。
f = open("C:/Users/John Green/Desktop/follows.txt", "r")
for line in f:
namelist = line.split()
names += len(namelist)
f.close()
print(names)
解决方案
您可以使用“列表”并制作列表列表。我会创建一个主列表来存储索引,然后附加从“split()”([“word1”,“wordN”])返回的列表。
因此,您可以简单地打印 max_index 指向的列表的第一项。
f = open("C:/Users/John Green/Desktop/follows.txt", "r")
word_list = []
max_index = 0
max_num_word = 0
for index,line in enumerate(f.readlines(),0):
namelist = line.split()
word_list[index].append(namelist) # adding the new list
if (max_num_word < len(namelist)):
max_num_word = len(namelist)
max_index = index
f.close()
print namelist[max_index][0] #first word of the most num words line
推荐阅读
- python - 在 PyQt 中使用 QProcess 运行类方法
- android - Play 商店中的更新按钮不适用于我的新更新
- intellij-idea - IntelliJ Ultimate 中没有 Web 应用程序选项
- python - 导入python字典变量,失败:AttributeError:'dict'对象没有属性
- python - 基于列表的打印python删除最后一个逗号
- java - Spring Boot 项目“org.springframework.beans.factory.BeanCreationException:创建名为“entityManagerFactory”的bean时出错”错误
- azure - 权限问题 + Azure AD
- apache-camel - REST API Camel 的拦截器
- javascript - 字符串替换,但仅适用于引号内的子字符串
- next.js - NextJS 和反应查询