【问题标题】:How to format tweets using python through twitter api?如何通过 twitter api 使用 python 格式化推文?
【发布时间】:2013-05-13 22:42:43
【问题描述】:

我通过 twitter api 收集了一些推文。然后我在python中使用split(' ')计算了单词。但是,有些词看起来是这样的:

correct! 
correct.
,correct
blah"
...

那么我怎样才能在没有标点符号的情况下格式化推文呢?或者也许我应该尝试另一种方式来split 推文?谢谢。

【问题讨论】:

  • 任何使用string.punctuation 的简单解决方案无疑都会混淆表情符号和其他特殊字符序列。如果您关心这一点,您应该考虑为推文使用标记器构建。

标签: python regex string twitter split


【解决方案1】:

您可以使用re.split对多个字符进行拆分...

from string import punctuation
import re

puncrx = re.compile(r'[{}\s]'.format(re.escape(punctuation)))
print filter(None, puncrx.split(your_tweet))

或者,只查找包含某些连续字符的单词:

print re.findall(re.findall('[\w#@]+', s), your_tweet)

例如:

print re.findall(r'[\w@#]+', 'talking about #python with @someone is so much fun! Is there a     140 char limit? So not cool!')
# ['talking', 'about', '#python', 'with', '@someone', 'is', 'so', 'much', 'fun', 'Is', 'there', 'a', '140', 'char', 'limit', 'So', 'not', 'cool']

我最初在示例中确实有一个笑脸,但当然这些最终会被这种方法过滤掉,所以要小心。

【讨论】:

    【解决方案2】:

    在进行拆分之前尝试从字符串中删除标点符号。

    import string
    s = "Some nice sentence.  This has punctuation!"  
    out = s.translate(string.maketrans("",""), string.punctuation)
    

    然后在out 上执行split

    【讨论】:

      【解决方案3】:

      我建议在使用此代码拆分之前清除特殊符号中的文本:

      tweet_object["text"] = re.sub(u'[!?@#$.,#:\u2026]', '', tweet_object["text"])
      

      您需要在使用函数 sub 之前导入 re

      import re
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2020-07-21
        • 2014-10-23
        • 1970-01-01
        • 2013-05-30
        • 2021-07-24
        • 2018-02-12
        • 2016-04-15
        • 2014-09-12
        相关资源
        最近更新 更多