我需要一个程序来接受字符串并提取特定单词以在Python中获得类似的输出?
输入字符串:
My name is somename. I am from India and I'm an Engineer.
输出应为:
Name: Somename
Location: India
Profession: Engineer
请,有人可以帮我吗?
答案 0 :(得分:1)
不清楚您要的是什么。
如果它是一个简单的正则表达式查询:
import re
strng = "My name is somename. I am from India and I'm an Engineer."
mobj = re.match("My name is (?P<name>.*). I am from (?P<location>.*) and I'm an (?P<profession>.*).", strng)
if mobj:
print("Name: {}".format(mobj.groupdict()['name']))
print("Location: {}".format(mobj.groupdict()['location']))
print("Profession: {}".format(mobj.groupdict()['profession']))
如果您想要更自然的语言解析器,请尝试Hiadore建议的选项:Spacy(spacy.io)或mitie(github.com/mit-nlp/MITIE)
答案 1 :(得分:0)
代码:-
import spacy
nlp = spacy.load('en')
doc2 = nlp("My name is John. I am from India and I'm an Engineer.")
print([(X.text, X.label_) for X in doc2.ents])
结果:-
[('John', 'PERSON'), ('India', 'GPE'), ('Engineer', 'PERSON')]