如何计算一个char

时间:2018-05-19 09:54:38

标签: python list for-loop

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

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

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:4)

选项1
使用 re.findall

collections.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