这是我的一句话:
s = "& how are you then? I am fine, % and i want to found some food #meat with vegetable# #tea# #cake# and #tea# so on."
我希望计算句子# #
中受s
约束的单词的频率。
我想要以下输出
[("meat with vegetable", 1)
("tea", 2)
("cake", 1)]
非常感谢您的帮助和时间!
答案 0 :(得分:1)
使用re
和Counter
的力量,可以轻松完成此任务:
In [1]: import re
In [2]: s = "& how are you then? I am fine, % and i want to found some food #meat with vegetable# #tea# #cake# and #tea# so on."
In [3]: re.findall(r'#([^#]*)#', s)
Out[3]: ['meat with vegetable', 'tea', 'cake', 'tea']
In [4]: from collections import Counter
In [5]: Counter(re.findall(r'#([^#]*)#', s))
Out[5]: Counter({'tea': 2, 'cake': 1, 'meat with vegetable': 1})
通过阅读python re和collections.Counter上的文档获取更多信息。