消息中有多少次?Python 2.x



text.txt的外观

星期五8月8日

名称 FRED @ All Hi Hi您过得如何

阅读乔治·汉娜·艾琳(George Hannah Irene)

星期五8月8日

名称 George @ Fred到目前为止还不错,您

阅读弗雷德·汉娜·艾琳(Fred Hannah Irene)

星期五8月8日

名称 Hannah @ Fred有点疲倦

弗雷德·乔治·艾琳(Fred George Irene)阅读

星期六8月9日

name irene @ @ ash you you thewever thewever at yeway

弗雷德·乔治·汉娜(Fred George Hannah)阅读

星期六8月9日

名称 Fred @ irene我想去溜冰

阅读乔治·艾琳(George Irene)

星期六8月9日

名称 irene @ Fred Let's Go

弗雷德·乔治(Fred George)阅读

星期六8月9日

名称 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..']

保留重复的名称。附录给了我一个没有重复名称的列表。

如何将所有输出名称获取列表中的所有输出名称?不确定如何定义我生成的输出名称列表。

我的最终目标是找到所有名称,并计算它们在text.txt文件中发生多少次。我正在考虑列出名称列表,然后将它们计数,但我不确定如何创建该列表要计算。我不想以bold的名字来计算@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

尝试

打印列表(output_name)给我

不需要的输出

[ 'f', 'r', 'e', 'd']

....

这不是我想要的。

预先感谢您的帮助!赦免我缺乏适当的行话,我仍然是Python的初学者程序员。

使用字典从列表中计算您的项目

fhand = open('text.txt')
names=[]
for line in fhand:
    line = line.rstrip()
    if not line.startswith('name ') : continue
    words = line.split()    
    output_name = words[1]
    names.append(output_name)
# which will give me just the BOLD names 
L = ['apple','red','apple','red','red','pear']
allcount = {}
[allcount .__setitem__(item,1+allcount.get(item,0)) for item in names]
print(allcount )

您也可以使用 regex

进行操作
import re
from collections import Counter
with open('text.txt', 'r') as f:
    data = f.read()
results = Counter(re.findall('(w+) @', data))
for name, value in results.items():
    print('{}: {}'.format(name, value))

输出:

fred: 2
george: 1
hannah: 1
irene: 2

您可以随时使用list.count,例如:

>>> ['fred', 'george', 'hannah', 'irene', 'fred', 'irene'].count('fred')
2

或在迭代时构建字典:

counter = {}
for line in fhand:
    line = line.rstrip()
    if not line.startswith('name ') : continue
    words = line.split()    
    output_name = word[1]
    try:
        counter[output_name] += 1
    except KeyError:
        counter[output_name] = 1

或使用内置Counter

>>> from collections import Counter
>>> Counter(['fred', 'george', 'hannah', 'irene', 'fred', 'irene'])
Counter({'fred': 2, 'irene': 2, 'george': 1, 'hannah': 1})

最后,从dict打印:

for name, count in counter.items():
    print("{}: {}".format(name, count)

您需要将计数添加到列表:

fhand = open('text.txt')
names = [] # an empty list to hold the names
for line in fhand:
    line = line.rstrip()
    if not line.startswith('name ') : continue
    words = line.split()    
    names.append(word[1])

现在names列表保留了名称。要计算频率,您可以执行以下操作:

import collections
freq = collections.Counter(names)

现在freq将是一个类似于字典的计数器对象,它将包含每个名称的出现数量。例如,freq['fred']将返回名称" Fred"的出现数量。

作为旁注,我建议不要在可能的情况下使用continue - 这会使代码不太清楚。而不是使用if ... else

fhand = open('text.txt')
names = [] # an empty list to hold the names
for line in fhand:
    line = line.rstrip()
    if line.startswith('name '):
        words = line.split()
        names.append(word[1])

这样,您的代码使您的意图("提取名称")更加清晰。

如果您现在想用频率结果做某事(即打印),则可以浏览字典:

for k, v in freq.items():
    print(k, v)

(当然,您可以使用print更好地格式化结果。)

您应该尝试创建一个词典并存储名称和出现的次数。

    from collections import defaultdict
    fhand = open('text.txt')
    name_count = defaultdict(int)    
    for line in fhand:
        line = line.rstrip()
        if not line.startswith('name ') : continue
        words = line.split()    
#        output_name = word[1]
        name_count[words[1]] += 1
    print(name_count)

最新更新