【问题标题】:how many times a name is in a message? python 2.x一个名字在消息中有多少次?蟒蛇2.x
【发布时间】: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


【解决方案1】:

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

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 )

【讨论】:

    【解决方案2】:

    您也可以使用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
    

    【讨论】:

      【解决方案3】:

      您可以随时使用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)
      

      【讨论】:

      • 谢谢!计数器的 try 和 except 部分在我的代码中工作!构建字典是我需要做的。
      【解决方案4】:

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

      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 将是一个Counter 对象,它类似于字典,将包含每个名称的出现次数。例如,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 来更好地格式化结果。)

      【讨论】:

      • 感谢您的 if .. else 建议!但是当我尝试 print names output: [] print freq output: Counter() 我做错了吗?我正在使用 python 2.x,这行得通吗?
      • collections.Counter 存在于 Python2 中并且应该可以工作。你到底尝试了什么?正如我所说,collections.Counter() 返回一个字典 - 也许您需要查找它并学习如何使用字典。简而言之,与其尝试调用print,不如在字典的项目上运行一个循环并打印每个项目。
      • 谢谢,我去查一下。另一个问题,是否有办法查看或检查名称列表中的内容?您说“现在名称列表包含名称。”但是当我尝试打印(名称)输出时我无法看到列表:什么都没有?我想知道如何创建该列表。
      • 如果您有具体问题,或者您尝试了一些代码但它没有按预期工作,最好提出一个新问题并提供完整的详细信息(请参阅here an how问)。另外,如果我可以建议的话,你问的是非常基本的问题,所以也许你应该寻找一个很好的 Python 和 Python 集合的基本教程。
      【解决方案5】:

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

          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)
      

      【讨论】:

      • 感谢您的帮助!但是当我尝试 print(name_count) 我得到输出: defaultdict(, {}) 我做错了什么吗?我正在使用 python 2.x,这行得通吗?
      • 是的。这将在 python 2.x 中工作。您可以尝试在循环中打印行和单词吗?此外,我的代码中有一个小错误。我使用的是“word”而不是“words”。
      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2012-11-19
      相关资源
      最近更新 更多