2013-08-10 2 views
2

У меня есть текстовое предложение: «Мой Отец - американец, и он красивый» и «Моя мама из Северной Америки, и она хороша».Идентификация строки перед заданной последовательностью слова

Мне нужно извлечь слово, которое находится перед словом 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*' 

ответ

1

Что-то вроде этого?

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 
+0

Что делать, если первое слово «Америка»? –

+0

Нет, это должно быть 2 предложения. «Мой Отец - американец, и он красив». это всего лишь одно предложение. – user1315906

+0

Ashwini Chaudhary: done –

4

Как насчет этого?

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'] 
3

Если вы собираетесь использовать регулярные выражения, ваш подход неверен. Просто проанализируйте все предложение. Взгляд вперед утверждение даст вам слово перед America или American:

re.findall(r'\w+(?=\s+American?)', line) 

Демо:

>>> line = 'My Father is an American, and he is handsome' 
>>> re.findall(r'\w+(?=\s+American?)', line) 
['an'] 
>>> line = 'My Mother is from North America and she is nice' 
>>> re.findall(r'\w+(?=\s+American?)', line) 
['North'] 

Это также работает на всего теле текста:

>>> 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'] 
0

вы могли бы попробовать это:

line = 'My Father is an American, and he is handsome' 

words = line.split() 
i = words.index("American,") 
print words[i-1] 

отпечатывается an

0

Я не уверен, как предложения разделяются, но если они находятся в списке предложений вы можете использовать.

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] 
+0

Могу ли я отредактировать это, чтобы добавить 2 слова 'America *' и 'Australia *'? – user1315906

+0

Да, вы можете сделать следующее: 're.search ((« America * | Australia *) », word)' – Bryan

Смежные вопросы