【问题标题】:python how to read file and store the sections into separated listspython如何读取文件并将部分存储到单独的列表中
【发布时间】:2019-11-05 07:16:56
【问题描述】:

我有一个这样的keywords.txt文件:

    #section1
    keyword1
    keyword2
    ......
    #section2
    keyword3
    keyword4
    ......
    #section3
    keyword5
    keyword6
    ......

每个部分都有很多关键字,并且有很多部分。我的问题是: 如何将每个部分提取到单独的列表中,如下输出:

    section1=["keyword1","keyword2"]
    section2=["keyword3","keyword4"]
    ......

这就是我所做的,提取分隔符“#”的行号

separator_numlist=[]
with open("keywords.txt") as f:
    for num,line in enumerate(f):
        if('#') in line:
            separator_numlist.append()
"""
Then read lines between each separator's line number
"""

有没有更好的解决方案? 另外我正在考虑将这些关键字存储在 XML 或 json 中,也许从结构化文件中读取部分比从 txt 文件中读取效率更高。

【问题讨论】:

    标签: python file keyword


    【解决方案1】:

    你可以使用字典:

    dic = dict()
    with open('output', 'r') as f:
        for i in f.readlines():
            if i.startswith('#'):
                my_key = i.replace("#", "")
                dic_key = my_key.strip()
            else:
                if dic_key in dic:
                    dic[dic_key] += [i.strip()]
                else:
                    dic[dic_key] = [i.strip()]
    

    输出:

    {'section1': ['keyword1', 'keyword2'], 'section2': ['keyword3', 'keyword4'], 'section3': ['keyword5', 'keyword6']}
    

    您也可以导入 json 并使用它来转换它:

    json_output = json.dumps(dic)
    

    【讨论】:

      【解决方案2】:

      像 LinPy 一样,我也建议使用 dict:

      with open( "split.txt" ) as fpntr:
          data = fpntr.read()
      
      out = {
          y[0] : y[1::] for y in [ x.split() for x in data.split('#') if x] 
          }
      
      print out
      

      给予

      {'section3': ['keyword5', 'keyword6'], 'section2': ['keyword3', 'keyword4'], 'section1': ['keyword1', 'keyword2']}
      

      if x 可以消除空刺。

      【讨论】:

      • Using list comprehensions instead of for-loops for side-effects, and dropping the list, is bad style。 for 循环没有任何问题。我删除了反对票,因为它实际上解决了问题。
      • @JanChristophTerasa here 第 1 节提到了你的“副作用”,并直接给出了一个例子,这些“副作用”实际上是一个有意义的目的。我认为我的代码是这些异常之一,尤其是在查看 for 循环解决方案中的所有 if else 语句时
      • 这不仅是一种糟糕的风格,而且还可能导致代码性能下降,因为根据问题的大小,您会无缘无故地创建大量内存开销。使用字典理解的新代码更好、更简洁、更简洁。
      • @JanChristophTerasa 同意,我不会将代码用于千兆字节数据文件....但是——说实话——我也不会使用 Python。
      猜你喜欢
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2023-01-19
      • 2021-06-03
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多