我有一个文本文件如下。
LA English
DT Article
GJ asthma; susceptible genes; natural language processing analysis; network
centrality analysis
ID LITERATURE-BASED DISCOVERY; CO-WORD ANALYSIS; UNDISCOVERED PUBLIC
KNOWLEDGE; INFORMATION-RETRIEVAL; FISH-OIL; SCIENTIFIC COLLABORATION;
INSULIN-RESISTANCE; COMPLEX NETWORKS; METFORMIN; OBESITY
GJ natural language processing; network analysis
GJ data mining; text mining; learning analytics; deep learning;
network centrality analysis我想要整行GJ条目。也就是说,我的最后输出应该如下。
[[asthma, susceptible genes, natural language processing analysis, network centrality analysis], [natural language processing, network analysis], [data mining, text mining, learning analytics, deep learning, network centrality analysis]]我正在使用下面的python程序。
with open(input_file, encoding="utf8") as fo:
for line in fo:
if line[:2].isupper():
if line[:2] == 'GJ':
temp_line = line[2:].strip()
next_line = next(fo)
if next_line[:2].isupper():
keywords = temp_line.split(';')
else:
mykeywords = temp_keywords + ' ' + next_line.strip()
keywords = mykeywords.split(';')
print(keywords)然而,我忽略下一行的方式存在一个问题。因此,根据我的程序,我没有将GJ (即[data mining, text mining, learning analytics, deep learning, network centrality analysis])的第三行作为输出列表。
如果需要,我很乐意提供更多的细节。
发布于 2019-05-07 00:09:56
让我们试着解决这个问题。代码中有两个主要的逻辑过程:
以下是代码:
def iter_lines(fo):
cur_line = []
for row in fo:
if not row.startswith(' ') and cur_line:
yield ' '.join(cur_line)
cur_line = [] # reset the cache
cur_line.append(row.strip())
# yield the last line
if cur_line:
yield ' '.join(cur_line)
with open(input_file, encoding="utf8") as fo:
for line in iter_lines(fo):
if line.startswith('GJ'):
keywords = [k.strip() for k in line[2:].split(';')]
print(keywords)发布于 2019-05-07 00:11:38
下面是您想要做的事情,并且可能通过一些调试就可以达到这个目的。
temp_keywords = ''
mykeywords = ''
with open(input_file, encoding="utf8") as fo:
for line in fo:
if line[:2].isupper():
if line[:2] == 'GJ':
temp_line = line[2:].strip()
next_line = next(fo)
temp_line += next_line.strip()
print (temp_line.split(';'))这里的问题是自己调用next(fo),而不是让for循环完成它的工作,这意味着您必须处理所有for循环的工作。因此,您在next_line中读取的内容将不会在下一个循环中处理。您将完全错过文件中的一些行。
相反,您总是希望让for循环处理它的工作。
但是这里有两种不同的分解文件的方法。编写记录解析器更容易找到完整的记录,并让它根据需要从文件中读取行。以下是我在评论中联系到的另一个答案的改编:
def is_new_record(line):
return line[:2].isupper()
def helper(text):
data = []
for line in text.readlines():
if is_new_record(line):
if (data):
yield ''.join(data)
data = [line.strip()]
else:
data.append(line.strip())
if (data):
yield ''.join(data)
# the helper is a generator for multiline records, as one line
input_file = 'data.txt'
with open(input_file) as f:
for record in helper(f):
print (record)LA英语 DT条款 哮喘;易感基因;自然语言处理分析;网络中心性分析 基于文献的发现;CO-字分析;未被发现的PUBLICKNOWLEDGE;信息检索;鱼油;科学协作;胰岛素抵抗;复杂网络;二甲双胍;肥胖 自然语言处理.网络分析 GJ数据挖掘;文本挖掘;学习分析;深度学习;网络中心性分析
https://stackoverflow.com/questions/56013523
复制相似问题