【发布时间】:2019-03-04 12:07:45
【问题描述】:
text.txt 的样子
8 月 8 日星期五
name fred @大家好,你好吗
乔治·汉娜·艾琳阅读
8 月 8 日星期五
name george @fred 到目前为止还不错,你
由弗雷德·汉娜·艾琳阅读
8 月 8 日星期五
name hannah@fred 有点累了
由弗雷德·乔治·艾琳阅读
8 月 9 日星期六
name irene @你们周末想做什么
由弗雷德·乔治·汉娜阅读
8 月 9 日星期六
name fred @irene 我想去滑冰
乔治·艾琳读
8 月 9 日星期六
name irene@fred 我们走吧
由弗雷德·乔治阅读
8 月 9 日星期六
name fred @ ....
等等 .... 更多信息
所以我得到了这部分代码
输入
fhand = open('text.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('name ') : continue
words = line.split()
output_name = word[1]
# which will give me just the BOLD names
但是我如何继续并完成代码,以便将这些名称的输出连接在一起?所以打印会在一个列表中
期望的输出
['fred', 'george', 'hannah', 'irene', 'fred', 'irene' 'etc..']
保留重复的名称。 append 给了我一个没有重复名称的列表。
如何获取列表中的所有输出名称?不确定如何定义我生成的输出名称列表。
我的最终目标是找到所有名称并计算它们在 text.txt 文件中出现的次数。我正在考虑制作一个名称列表,然后将它们计数,但我不确定如何创建该列表以进行计数。我不希望它只计算@name 粗体的来自名称的名称。每个人发了多少次消息?
期望的最终输出
fred: 3 # or actual number times of occurrence / count
george: 1 # or actual number times of occurrence / count
hannah: 1 # or actual number times of occurrence / count
irene: 2 # or actual number times of occurrence / count
试过
打印列表(输出名称)给我
不需要的输出
[ 'f', 'r', 'e', 'd']
....
这不是我想要的。
提前感谢您的帮助! 请原谅我缺乏正确的行话,我仍然是 python 的初学者程序员。
【问题讨论】:
-
我不确定如何用所有这些来创建字典...
-
我知道如何创建字典部分(我想),但不确定如何让我的名字列表在字典中计数。如何生成名称列表?
标签: python string list count output