【发布时间】:2018-05-02 13:43:45
【问题描述】:
试图找到一种方法使这个过程以 Python 方式或根本不工作。基本上,我有一个很长的文本文件,它被分成几行。每 x 行有一个主要是大写的,大致应该是该特定部分的标题。理想情况下,我希望标题和之后的所有内容都使用标题作为文件名进入文本文件。在这种情况下,这必须发生 3039,因为那里会有尽可能多的标题。 到目前为止,我的过程是这样的:我创建了一个通过文本文件读取的变量,告诉我它是否主要是大写的。
def mostly_uppercase(text):
threshold = 0.7
isupper_bools = [character.isupper() for character in text]
isupper_ints = [int(val) for val in isupper_bools]
try:
upper_percentage = np.mean(isupper_ints)
except:
return False
if upper_percentage >= threshold:
return True
else:
return False
之后,我做了一个计数器,这样我就可以创建一个索引,然后我把它组合起来:
counter = 0
headline_indices = []
for line in page_text:
if mostly_uppercase(line):
print(line)
headline_indices.append(counter)
counter+=1
headlines_with_articles = []
headline_indices_expanded = [0] + headline_indices + [len(page_text)-1]
for first, second in list(zip(headline_indices_expanded, headline_indices_expanded[1:])):
article_text = (page_text[first:second])
headlines_with_articles.append(article_text)
据我所知,所有这些似乎都运行良好。但是当我尝试打印我想要归档的部分时,我所能做的就是将整个文本打印到所有 txt 文件中。
for i in range(100):
out_pathname = '/sharedfolder/temp_directory/' + 'new_file_' + str(i) + '.txt'
with open(out_pathname, 'w') as fo:
fo.write(articles_filtered[2])
编辑:这让我走到了一半。现在,我只需要一种用第一行命名每个文件的方法。
for i,text in enumerate(articles_filtered):
open('/sharedfolder/temp_directory' + str(i + 1) + '.txt', 'w').write(str(text))
【问题讨论】:
标签: python python-3.x nlp nltk