如何使用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"))

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

输入文本文件示例:-

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

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

教育 机构名称:SOUTHVILLE FOREIGN UNIVERSITY-PHILIPPInes 位置霍姆作为菲律宾机构Pinas市的开始日期:( 2007年6月

必需的输出:-

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

我必须在文本文件中搜索“培训目标关键字”,发现它只能写下5行。

zishanwangzhe 回答:如何使用python

如果您只是尝试提取整个“ Training Objectives”(训练目标)块,请寻找关键字并保持追加行,直到您击中空白行(或其他合适的标记,例如下一个标题)。

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

const regex = /^\/search\/((?:\d{4}))(?:\/((?:\d|1[012]|0[1-9])))?(?:\/((?:[0-3]\d)))/
const testLink = [
  '/search/2017/02/03/category/gun/','/search/2017/01/category/gun/','/search/2017/category/gun/','/search/2017/02/03/category/gun/','/search/2018/?category=gun&type%5B%5D=sendo'

]

testLink.forEach((value,i) => {
  console.log(value.replace(regex,''))
  console.log('-------------------')
})

这假定每个文件中只需要1个块。如果您要从每个文件中提取多个块,它将变得更加复杂。

如果您确实总是且每次都需要5行,那么您可以执行类似的操作,但添加一个计数器来计数5行。

,

尝试一下:

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

这取决于您所处的位置,但是我将正则表达式放在一起可能有助于举例说明我的文本在变量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']
本文链接:https://www.f2er.com/3147151.html

大家都在问