Python从文件

时间:2016-03-04 17:44:09

标签: python python-3.x text-extraction

我有一个包含

等数据的文本文件
Tweet_id:"123456789", "text":"What an episode", "truncated":"false",Tweet_id:"12345678910", "text":My number is fascinating", "truncated":false

我想只提取文本字段

Tweet_id:"123456789", **"text":"What an episode", "truncated"**:"false",Tweet_id:"12345678910", **"text":My number is fascinating", "truncated":false**

2 个答案:

答案 0 :(得分:2)

This is a natural application of regular expressions.

import re

text_re = re.compile("""
    "text":"            # This matches the part right before what you want.
    (?P<content>[^"]+)  # Matches the content
    "                   # Matches the close-quote after the content.
""", re.VERBOSE)

for match in text_re.finditer('Tweet_id:"123456789","text":"What an episode","truncated":"false,Tweet_id:"12345678910","text":"My number is fascinating","truncated":false"'):
    print match.group('content')

This will print:

What an episode
My number is fascinating

The regular expression may need to get more complicated depending on the details of how consistently the data is formatted, how double-quote characters in the content of the tweet are handled in the data, etc.

答案 1 :(得分:1)

I am not sure which part exactly You want to extract but I suggest You to use regular expressions.

>>> import re
>>> string = 'Tweet_id:"123456789","text":"What an episode","truncated":"false,Tweet_id:"12345678910","text":My number is fascinating","truncated":false'
>>> re.findall('\"text\":(.*?),', string)
['"What an episode"', 'My number is fascinating"']
相关问题