首页 > 解决方案 > 读取具有以特殊字符开头的行的 .txt 文件

问题描述

我正在尝试读取以不同特殊字符开头的文件中的每一行。我不想只阅读下一行的其余部分的那些特殊字符。记录在文件中显示如下: 在此处输入图像描述 然后我需要将每个文档存储在数据框的行中。

这是我尝试过的:

Doc = namedtuple('Doc', 'venue year authors title id references abstract')
docs = []

with open('/content/test.txt') as f:
  for l in f.readlines():
   ln = l.rstrip('\n')
   if  ln.startswith('#c'):
    venue = ln[2:]
    #print(venue)
   if  ln.startswith('#t'):
     year = ln[2:]
     #print(year)
   if  ln.startswith('#@'):
     authors = []
     author = ln[2:]
     authors.append(author)
   if  ln.startswith('#*'):
     title = ln[2:]
   if  ln.startswith('#index'):
     id = ln[2:]
   if ln.startswith('#%'):
        references = []
        reference = ln[2:]
        references.append(reference)
   if  ln.startswith('#!'):
     abstract = ln[2:]
     print(abstract)
     docs.append(Doc(venue, year, authors, title, id, references, abstract))

   df = pd.DataFrame.from_records(docs, columns= 
   ['Venue','Year','Authors','Title','id', 'ListCitations','Abstract'])
df

有人可以帮我解决将变量作为作者和参考文献存储在列表中的问题吗?谢谢

标签: pythonpython-3.xdataframe

解决方案


终于解决了所有问题###########

修复了我猜你缺少一些引用的代码,所以我只是导入了它们。同样在运行代码之前,您可能需要安装下面提到的名为 pandas 的包

我目前使用的是 python 3.8,如果您使用的是 python 2 版本,那么您可能想跳过 pip 命令中的 3

pip3 install pandas

代码:

from collections import namedtuple
import pandas as pd

Doc = namedtuple('Doc', 'venue year authors title id references abstract')
docs = []

f = open("content/test.txt", "r")

while(True):
    # Read a line.
    #if not ln.startswith("#t") or not ln.startswith("#index"):
    ln = f.readline()
    print('{} : {}'.format("LINE : ", ln))
    ln = ln.rstrip('\n')
    
    # When readline returns an empty string, the file is fully read.
    if ln == "":
        print("::DONE::")
        break
    # When a newline is returned, the line is empty.
    if ln == "\n":
        #print("::EMPTY LINE::")
        continue
    if ln.startswith('#c'):
        venue = ln[2:]
        print(venue)
    if ln.startswith('#t'):
        year = ln[2:]
        print(year)
    if ln.startswith('#@'):
        authors = []
        while not ln.startswith('#t'):
            if ln.startswith('#@') :
                author = ln[2:]
            else:
                author = ln[0:]
            authors.append(author)
            ln = f.readline()
            print(author)
        f.seek(f.tell() - len(ln))
        ",".join(authors)
    if ln.startswith('#*'):
        title = ln[2:]
        print(title)
    if ln.startswith('#index'):
        id = ln[6:]
        print(id)
    if ln.startswith('#%'):
        references = []
        while not ln.startswith('#!'):
            reference = ln[2:]
            references.append(reference)
            ln = f.readline()
            print(reference)
        ",".join(references)    
    if  ln.startswith('#!'):
        abstract = ln[2:]
        print(abstract)
        docs.append(Doc(venue, year, authors, title, id, references, abstract))

df = pd.DataFrame.from_records(docs, columns= 
                ['Venue','Year','Authors','Title','id', 'ListCitations','Abstract'])

pd.set_option("display.max_rows", None, "display.max_columns", None)
print(df)

测试输入:

#*Information geometry of U-Boost and Bregman divergence
#@Nobotu Murata,
Takenouchi
Takafumi Kanamori
#t2004
#cNeural Computation
#index436405
#%94584
#%282290
#%605546
#%620759
#%564878
#!We aim at an extension of AdaBoost to U-Boost
#*Paper 2
#@Tareq 
Shareq
Sameena
#t2016
#cSimulation Computation
#index436406
#%94584
#%282291
#%605543
#%620754
#%323232232232323
#!We aim to conquere the world

输出:

                Venue  Year  \

0 神经计算 2004
1 模拟计算 2016

                                         Authors  \

0 [村田伸,, Takenouchi\n, Takafumi Kanamo...
1 [Tareq , Shareq\n, Sameena\n]

                                           Title      id  \

0 U-Boost 和 Bregman di... 的信息几何 436405
1 论文 2 436406

                                   ListCitations  \

0 [94584, 282290\n, 605546\n, 620759\n, 564878\n]
1 [94584, 282291\n, 605543\n, 620754\n, 32323223...

                                      Abstract  

0 我们的目标是将 AdaBoost 扩展到 U-Boost\n
1 我们的目标是征服世界\n


推荐阅读