【发布时间】:2018-11-08 12:58:52
【问题描述】:
编程新手,已经找到了很多有用的线程,但不是我需要的。
我有一个看起来像这样的文本文件:
1 of 5000 DOCUMENTS
Copyright 2010 The Deal, L.L.C.
All Rights Reserved
Daily Deal/The Deal
January 12, 2010 Tuesday
HEADLINE: Cadbury slams Kraft bid
BODY:
On cue .....
......
body of article here
......
DEAL SIZE
$ 10-50 Billion
2 of 5000 DOCUMENTS
Copyright 2015 The Deal, L.L.C.
All Rights Reserved
The Deal Pipeline
September 17, 2015 Thursday
HEADLINE: Perrigo rejects formal offer from Mylan
BODY:
(and here again the body of this article)
DEAL SIZE
作为输出,我只希望在一个文件中的新行中的每篇文章的正文(每个文章正文一个单元格)(我有大约 5000 篇文章要像这样处理)。输出将是 5000 行和 1 列。 从我的发现看来,'re' 将是最好的解决方案。所以重复出现的关键字是 BODY: 可能还有 DOCUMENTS。如何仅将这些关键字之间的文本提取到 Excel 中每篇文章的新行中?
import re
inputtext = 'F:\text.txt'
re.split(r'\n(?=BODY:)', inputtext)
还是这样的?
section = []
for line in open_file_object:
if line.startswith('BODY:'):
# new section
if section:
process_section(section)
section = [line]
else:
section.append(line)
if section:
process_section(section)
我有点迷失在哪里看,提前谢谢!
编辑:感谢 ewwink,我现在在这里:
import re
articlesBody = None
with open('F:\CloudStation\Bocconi University\MSc. Thesis\\test folder\majortest.txt', 'r') as txt:
inputtext = txt.read()
articlesBody = re.findall(r'BODY:(.+?)\d\sDOCUMENTS', inputtext, re.S)
#print(articlesBody)
#print(type(articlesBody))
with open('result.csv', 'w') as csv:
for item in articlesBody:
item = item.replace('\n', ' ')
csv.write('"%s",' % item)
【问题讨论】:
标签: python regex text extract sentiment-analysis