【问题标题】:Using regex to retrieve specific text使用正则表达式检索特定文本
【发布时间】:2018-01-20 17:37:51
【问题描述】:
tweets = re.findall(r "'text':+.*'truncated'", tweets)

print (tweets)

'text': "RT @premierleague: ???? @WayneRooney 的追逐正在进行 ????", 'truncated':

我有一个像上面这样的文本字符串,我想检索介于 'text': and 'truncated' 之间的推文。

我已经写了上面的代码但是收到错误信息

 tweets = re.findall(r "'text':+.*'truncated'", tweets)
                                                ^
SyntaxError: invalid syntax

我正在使用 findall 重复推文,我想从 findall 搜索中检索所有推文。

谢谢。

【问题讨论】:

  • 您确定不想利用字符串的 json 结构并使用 json 模块吗?

标签: python regex python-3.x twitter


【解决方案1】:

无效语法错误是由于r 和正则表达式之间的空格

tweets = re.findall(r"'text':+.*'truncated'", tweets)
print(tweets)

返回:

['\'text\': "RT @premierleague: \xf0\x9f\x94\xb5 @WayneRooney\'s chase is on \xf0\x9f\x91\x80", \'truncated\'']

仅检索文本:

tweets = re.findall(r"'text':+(.*)'truncated'", tweets)
print(tweets)

返回:

 "RT @premierleague: ? @WayneRooney's chase is on ?", 

【讨论】:

  • 是的,你也可以使用圆括号来获取文本。
  • 感谢您的提醒 r.e.白色空间。我希望它会删除所有我不想要的文本,但它只是返回了 api 搜索。
  • @LukeSimpson 我更新了上面的答案以仅检索文本。请注意,如果可能的话,只解析 JSON 可能会更容易(在 Python 中使用 json.loads)。
  • @LukeSimpson 你想让我详细说明一下以接受答案吗?
  • 嗨,请。仍然不是只检索 text 和 truncated 之间的文本。
猜你喜欢
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多