【问题标题】:How to extract limited lines of data from specific keyword using python如何使用python从特定关键字中提取有限的数据行
【发布时间】:2019-11-07 06:10:30
【问题描述】:

我有一个文本文件,我需要提取段落中出现指定关键字的前五行。

我能够找到关键字,但无法从该关键字写下五行。

mylines = []                              

with open ('D:\\Tasks\\Task_20\\txt\\CV (4).txt', 'rt') as myfile:  

    for line in myfile:                   

        mylines.append(line)             

    for element in mylines:               

        print(element, end='')  

print(mylines[0].find("P"))

如果有人对此有任何想法,请提供帮助。

输入文本文件示例:-

菲律宾合作伙伴机构:ALL POWER STAFFING SOLUTIONS, INC.

培训目标: : 有国际文化接触和该领域的实践经验 将酒店管理作为通往有意义的酒店事业的门户。发展我的热情好客 管理技能并具有全球竞争力。

教育 机构名称:南维尔外国大学 - 菲律宾 地点 Hom 作为菲律宾 Pinas City 机构开始日期:(2007 年 6 月

所需输出:-

培训目标: : 有国际文化接触和该领域的实践经验 将酒店管理作为通往有意义的酒店事业的门户。发展我的热情好客 管理技能并具有全球竞争力。

#

我必须在文本文件中搜索 Training Objective Keyword,它发现它应该只写下 5 行。

【问题讨论】:

    标签: python text nlp nltk text-extraction


    【解决方案1】:

    如果您只是想提取整个“培训目标”块,请查找关键字并继续添加行,直到找到空行(或其他合适的标记,例如下一个标题)。

    (编辑处理多个文件和关键字)

    def extract_block(filename, keywords):
        mylines = []
        with open(filename) as myfile:
            save_flag = False
            for line in myfile:
                if any(line.startswith(kw) for kw in keywords):
                    save_flag = True
                elif line.strip() == '':
                    save_flag = False
                if save_flag:
                    mylines.append(line)
        return mylines
    
    filenames = ['file1.txt', 'file2.txt', 'file3.txt']
    keywords = ['keyword1', 'keyword2', 'keyword3']
    for filename in filenames:
        block = extract_block(filename, keywords)
    
    

    这假设每个文件中只有 1 个块。如果你从每个文件中提取多个块,它会变得更加复杂。

    如果您真的每次都想要 5 行,那么您可以做类似的事情,但添加一个计数器来计算您的 5 行。

    【讨论】:

    • 嘿,我有多个具有不同关键字的文本文件,所以请告诉我如何阅读所有文本文件,并根据该文件中存在的多个关键字提取段落。
    • @Ani 我已经更新了我的答案来处理多个文件和关键字。
    【解决方案2】:

    这取决于你在哪里\n,但我将一个正则表达式放在一起,这可能有助于我的文本在变量 st 中的外观示例:

    In [254]: st                                                                                  
    
    Out[254]: 'Philippine Partner Agency: ALL POWER STAFFING SOLUTIONS, INC.\n\nTraining Objectives::\nTo have international cultural exposure and hands-on experience \nin the field of hospitality management as a gateway to a meaningful hospitality career. \nTo develop my hospitality management skills and become globally competitive.\n\n\nEducation Institution Name: SOUTHVILLE FOREIGN UNIVERSITY - PHILIPPINES Location Hom as Pinas City, Philippine Institution start date: (June 2007\n'
    
    impore re
    
    re.findall('Training Objectives:.*\n((?:.*\n){1,5})', st)   
    
    Out[255]: ['To have international cultural exposure and hands-on experience \nin the field of hospitality management as a gateway to a meaningful hospitality career. \nTo develop my hospitality management skills and become globally competitive.\n\n\n']
    

    【讨论】:

      【解决方案3】:

      试试这个:

      with open('test.txt') as f:
          content = f.readlines()
      index = [x for x in range(len(content)) if 'training objectives' in content[x].lower()]
      for num in index:
          for lines in content[num:num+5]:
              print (lines)
      

      如果你只有几个单词(只是为了获取索引):

      index = []
      for i, line in enumerate(content):
          if 'hello' in line or 'there' in line:     //add your or + word here
              index.append(i)
      print(index)
      

      如果你有很多(只是为了获取索引):

      list = ["hello","there","blink"]    //insert your words here
      index = []
      for i, line in enumerate(content):
          for items in list:
              if items in line:
                  index.append(i)
      print(index)
      

      【讨论】:

      • 我确信有一种更短的方法,但是对于这个方法,我使用这些关键字获取行的索引并用您需要的额外行打印它们。
      • 只有一个关键字才能正常工作,我想给出多个关键字,找到每个关键字后,它应该写下五行...
      • 查看我的编辑。我希望你能掌握这个概念并按照你想要的方式进行编辑。
      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多