如何使用python从特定关键字中提取有限的数据行

2024-04-27 16:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我能够找到关键字,但不能从关键字写下五行

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"))

如果有人知道怎么做,请帮忙

输入文本文件Example:- 你知道吗

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

培训目标:具有国际文化接触和实践经验 酒店管理作为一个有意义的酒店事业的门户。来培养我的热情好客 管理技能和全球竞争力

教育 机构名称:菲律宾南维尔外国大学 地点:Hom as Pinas City,Philippine Institution开始日期:2007年6月

必需Output:- 你知道吗

培训目标:具有国际文化接触和实践经验 酒店管理作为一个有意义的酒店事业的门户。来培养我的热情好客 管理技能和全球竞争力

#

我必须搜索文本文件中的培训目标关键字和那些它发现,它应该写下5行只有


Tags: intxt目标forasline关键字element
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)

如果您只是试图提取整个“Training Objectives”块,请查找关键字并不断追加行,直到找到空行(或其他合适的标记,例如下一个标题)

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

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)

这假设每个文件中只需要一个块。如果要从每个文件中提取多个块,则会变得更复杂

如果你真的想要5行,总是和每次,那么你可以做一些类似的事情,但添加一个计数器来计算出你的5行

这取决于您所在的位置,但我将一个正则表达式放在一起,这可能有助于在变量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']

相关问题 更多 >