Python 识别给定单词序列前面的字符串
我有一个文字句子“我父亲是美国人,他很帅”和“我母亲来自北美,她很好” 我需要提取单词Python 识别给定单词序列前面的字符串,python,regex,Python,Regex,我有一个文字句子“我父亲是美国人,他很帅”和“我母亲来自北美,她很好” 我需要提取单词American(在本例中为an)和America(在本例中为North)前面的单词,以显示在控制台上 注意:单词America在第二句中有一个后缀America+n,使其成为American 我的代码到目前为止::: for line in words: for word in line.strip().split(' '): // HERE I SHOULD WRITE THE C
American
(在本例中为an
)和America
(在本例中为North
)前面的单词,以显示在控制台上
注意:单词America
在第二句中有一个后缀America+n
,使其成为American
我的代码到目前为止:::
for line in words:
for word in line.strip().split(' '):
// HERE I SHOULD WRITE THE CODE TO IDENTIFY THE WORD BEFORE THE STRING 'AMERICA*'
这个怎么样
import re
s = """
My Father is an American, and he is handsome
My Mother is from North America and she is nice
"""
print re.findall(r"(\w+)\sAmerica", s)
印刷品:
['an', 'North']
如果要使用正则表达式,您的方法是不正确的。把整个句子分析一下。前瞻性断言将给出
美国
或美国
之前的单词:
re.findall(r'\w+(?=\s+American?)', line)
演示:
这也适用于整个文本:
>>> text = '''\
... My Father is an American, and he is handsome
... My Mother is from North America and she is nice
... '''
>>> re.findall(r'\w+(?=\s+American?)', text)
['an', 'North']
像这样的
x='My Father is an American, and he is handsome. My Mother is from North America and she is nice'
y = x.split()[1:]
for (i,j) in enumerate(y):
if j.startswith('America'):
print y[i-1]
an
North
你可以试试这个:
line = 'My Father is an American, and he is handsome'
words = line.split()
i = words.index("American,")
print words[i-1]
这将打印一个我不确定这些句子是如何分开的,但它们是否在你可以使用的句子列表中
import re
for line in sentences:
sentence = line.strip().split(" ")
for word in sentence:
if re.search("America*",word):
ind = sentence.index(word)
print sentence[ind-1]
如果第一个单词是“美国”怎么办?不,应该是两句话我的父亲是美国人,他很英俊。这只是一句话。我可以编辑一下,这样我就可以添加两个单词
America*
和Australia*
?是的,你可以这样做:re.search((“America*.\124; Australia*),word)
import re
for line in sentences:
sentence = line.strip().split(" ")
for word in sentence:
if re.search("America*",word):
ind = sentence.index(word)
print sentence[ind-1]