首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计数焦炭

如何计数焦炭
EN

Stack Overflow用户
提问于 2018-05-19 09:54:37
回答 1查看 59关注 0票数 2

我有一个文件如下所示,我想数一数人们提到其他人的次数:

代码语言:javascript
复制
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

我试着用:

代码语言:javascript
复制
for line in fhand:
    if "@" in line:
        indexStart = line.find("@")

但我不知道接下来会发生什么。预期产出如下:

代码语言:javascript
复制
tom 5
amy 3
edwin 3
peter 5
john 1

有什么办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-19 10:00:08

选项1

re.findallcollections.Counter

代码语言:javascript
复制
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解释:

代码语言:javascript
复制
(?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

代码语言:javascript
复制
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的边缘

代码语言:javascript
复制
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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50423965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档