【问题标题】:How to count a char如何计算一个字符
【发布时间】:2018-05-19 09:54:37
【问题描述】:

我有一个文件如下,我想统计人们提到别人的次数:

peter @amy 
tom @amy 
tom @amy 
peter @tom 
edwin @amy
amy @peter 
tom @john @peter
amy @edwin 
tom  @peter
peter @john 
peter @john
john  @tom?
edwin @john
edwin @amy 
amy @tom

我尝试使用:

for line in fhand:
    if "@" in line:
        indexStart = line.find("@")

但我不知道接下来会发生什么。预期的输出是:

tom 5
amy 3
edwin 3
peter 5
john 1

有什么办法吗?

【问题讨论】:

  • 请拨打tour。 “这不是论坛。没有闲聊。”
  • 我只是需要一些想法。
  • @Louis 我将编辑您的问题以考虑与您相关的内容。这不是问题,您只会发现 SO 往往是事实,这可能会让新用户感到不舒服,但这意味着您的问题在未来对其他人来说会更快/更容易理解:)。欢迎使用 Stack Overflow。

标签: python list for-loop


【解决方案1】:

选项 1
re.findallcollections.Counter

import re
from collections import Counter

with open('test.txt') as f:
  data = re.findall(r'(?m)^(\w+).*@.*$', f.read())
  print(Counter(data))

# Counter({'tom': 5, 'peter': 4, 'edwin': 3, 'amy': 3, 'john': 1}) 

regex解释:

(?m)             # asserts multiline matching
^                # asserts position at the start of the line
(\w+)            # captures any word character in group 1 (this is the name you want)
.*               # Greedily matches any character besides line breaks
@                # Matches an @ symbol
.*               # Greedily matches any character besides line breaks
$                # Asserts position at end of line

如果您确实需要他们提及人的次数,而不仅仅是他们提及人的行数

选项 2
使用 collections.defaultdict

with open('test.txt') as f:
  dct = defaultdict(int)
  for line in f:
    dct[line.split()[0]] += line.count('@')
  print(dct)

# defaultdict(<class 'int'>, {'peter': 5, 'amy': 3, 'tom': 5, 'edwin': 3, 'john': 2})

选项 3
pandas 一起生活在边缘:

import pandas as pd

with open('test.txt') as f:
  data = [i.split(' ', 1) for i in f.read().splitlines()]
  df = pd.DataFrame(data)
  print(df.groupby(0).sum()[1].str.count('@'))

# Result

0
amy      3
edwin    3
john     2
peter    5
tom      5

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2014-12-25
    • 2021-07-10
    • 2016-06-24
    • 2019-11-24
    • 2021-12-26
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多