需要使用python根据其标题提取内容



我需要根据标题提取文本,假设在下面的代码中,我需要显示体验字段。比如,假设我有一个文本文件作为ab.text,其中包含以下数据:

Name: xyz
Experience: 
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019
Skills:
Python, MachineLearning, Java.

现在我需要读取此文本文件并仅显示经验字段下的文本。注意:姓名、经验和技能的顺序可能会有所不同。我是python的新手,请帮助我。

预期输出:

Experience: 
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019
您可以使用

re模块并使用它解析文本:

data = '''Name: xyz
Experience:
123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019
Skills:
Python, MachineLearning, Java.'''
import re
#Step 1. Split the string
s = [g.strip() for g in re.split('^(w+):', data, flags=re.M) if g.strip()]
# s = ['Name', 'xyz', 'Experience', '123 company 2016-2017n567 company 2017-2018nyzx company 2018-2019', 'Skills', 'Python, MachineLearning, Java.']
#Step 2. Convert the splitted string to dictionary
d = dict(zip(s[::2], s[1::2]))
# d = {'Name': 'xyz', 'Experience': '123 company 2016-2017n567 company 2017-2018nyzx company 2018-2019', 'Skills': 'Python, MachineLearning, Java.'}
print(d['Experience'])

指纹:

123 company 2016-2017
567 company 2017-2018
yzx company 2018-2019

我认为您设置的问题并没有很好地定义。但是根据您提供的示例文件,以下代码将起作用。您应该了解有关文件 I/O、列表方法和列表推导式的一些知识,以了解有关以下代码的更多信息。我试图以一种每次运行一行时都可以调查该行的作用的方式来构建它,这样代码看起来就不像魔术了。

f = open('C:/ab.text') # change ot the path of your file
contents = f.read() #read the contents
contents = contents.split('n') # turn the read object into a list
contents = [x.strip() for x in contents] #remove whitespace from elements
# below we concatentate the list so it starts at the Experience: row
contents = contents[contents.index('Experience:'):] 
# make a list of all the lines containing colons ':'
colon_places = [i for i,x in enumerate(contents) if x.find(':')>0] 
#if there is only one colon it will be at the start from 'Experience:'
if colon_places == [0]:
    contents=  contents
#if there is more than one, we only want to go as far as the second
elif len(colon_places) > 1:
    contents = contents[0:colon_places[1]]
#finally, we throw out the header 'Experience' and any empty rows
Experience = [x for x in contents if x  not in ['Experience:', '']]

我希望它对您有所帮助。

这将解决问题

法典

matches = re.findall('^Experience:.*[(d+ w+ d+-d+)n]+$', text, re.M)
for match in matches:
    print(match.strip())
    print()

解释

^经验

表示我们的匹配应以单词开头Experience

[(\d+ \w+ \d+

-\d+(]+

将匹配模式123 company 2016-2017一次或多次

$

末尾表示模式在模式123 company 2016-2017耗尽时结束一次

再。米

指示我们的输入文本是多行字符串,而不是单个长文本

最新更新