python - 如何计算一个字符
问题描述
我有一个文件如下,我想计算人们提到其他人的次数:
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
有没有办法做到这一点?
解决方案
选项
re.findall
1collections.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
推荐阅读
- php - 如何在 Laravel 中获取月度考勤报告
- php - 为 php 安装 sql server 驱动程序
- swift - 双转换错误 tvOS
- docker - 如何停止 VS2017 准备 docker 镜像
- angular - 将元素添加到 mat-tab-group 元素
- ruby-on-rails - 如何为关系传递序列化程序
- javascript - 使用 JavaScriptExecutor Selenium Java 更改 div 的样式高度
- angular - 类型脚本 - 角度:静态注入器错误
- cakephp-3.0 - CakePHP 3.6 Query Builder 复杂的 OR 条件问题
- python - 字典列表:遍历关键内容