我在使用python时遇到了一个问题。 我有一个txt文件,里面有500篇论文的摘要, 我要做的是把这个txt文件分成500个文件,每个txt文件只包含一个摘要。 现在,我发现,对于每个摘要,在末尾都有一行,以“PMID”开头,所以我考虑按这一行拆分文件。 但我对python还是个新手。 有什么想法吗? 提前谢谢。在
txt文件如下所示:
1. Ann Intern Med. 2013 Dec 3;159(11):721-8. doi:10.7326/0003-4819-159-11-201312030-00004.
text text text texttext texttext texttext texttext texttext texttext texttext text
text texttext texttext texttext texttext texttext text
text texttext texttext texttext texttext text
PMID: 24297188 [PubMed - indexed for MEDLINE]
2. Am J Cardiol. 2013 Sep 1;112(5):688-93. doi: 10.1016/j.amjcard.2013.04.048. Epub
2013 May 24.
text texttext texttext texttext texttext texttext texttext texttext texttext text
text texttext texttext texttext texttext texttext texttext texttext texttext text
PMID: 23711805 [PubMed - indexed for MEDLINE]
3. Am J Cardiol. 2013 Aug 15;112(4):513-9. doi: 10.1016/j.amjcard.2013.04.015. Epub
2013 May 11.
text texttext texttext texttext texttext texttext texttext texttext texttext text
text texttext texttext texttext texttext texttext texttext texttext texttext text
PMID: 23672989 [PubMed - indexed for MEDLINE]
等等。在
有很多方法可以做到这一点。有一种方法。 如果数据在名为
data
的文件中:印刷品
^{pr2}$取消最后两行的注释以将块保存到单独的文件中。在
为什么这么复杂?
对于短文件,您可以简单地将整个文件读入一个字符串,然后使用正则表达式拆分字符串。上面的解决方案是对这种可以处理大文件的思想的改编。它以块的形式读取文件,找到要拆分块的位置,并在找到块时返回块。在
处理由分隔符regex模式分隔的文件块的问题经常出现。因此,与其为每一个都编写一个定制的解决方案,不如使用像
open_chunk
这样的实用程序函数来处理所有这些问题,而不管分隔符是什么,而且它的处理方式既可以处理大文件,也可以处理小文件。在你可以试试:
注意,每个块中的最后一个换行符被删除。块可以写入单独的文件中。在
相关问题 更多 >
编程相关推荐