【问题标题】:Python - retrieve a specific sentence from a large text filePython - 从大文本文件中检索特定句子
【发布时间】:2015-07-23 02:45:16
【问题描述】:

这是我的句子:

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)]

非常感谢您的帮助和时间!

【问题讨论】:

  • 考虑我对你帖子的修改!
  • 感谢您的精彩修改
  • 您自己尝试过什么吗?这不是代码编写服务
  • ['素肉', '茶', 'cake', 'tea'] Counter({'tea': 2, 'cake': 1, '素肉': 1} )
  • this 现在对应 'piglei's advice ,我得到以下结果,['meat with vegetables', 'tea', 'cake', 'tea'] Counter({'tea': 2, “蛋糕”:1,“蔬菜肉”:1})

标签: python list count frequency


【解决方案1】:

利用reCounter的强大功能,这项任务可以轻松完成:

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 recollections.Counter 上的文档获取更多信息。

【讨论】:

  • 我是python新手,你的意思是使用re.find()和re.count()?
  • 请多点赞,我是python新手
  • 非常感谢,我仔细阅读了您的帖子,现在我明白了。谢谢
  • 这里我得到了一个txt文件,里面有很多不同的句子,你知道如何导入为s吗?
  • 感谢您的点击,现在我解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
相关资源
最近更新 更多