2013-08-10 2 views
2

저는 '내 아버지는 미국 사람이고 그는 잘 생겼어.'그리고 '내 어머니는 북미 출신이고 그녀는 좋다'라는 텍스트 문장을 가지고 있습니다.주어진 일련의 단어 앞에있는 문자열을 확인하십시오.

I는 콘솔에 표시되도록 (이 경우에는 North) 및 America (이 경우에는 an) 단어 American 앞에있는 단어를 추출 할 필요가있다.

참고 : 단어 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

:이 또한 텍스트의 전체 몸에서 작동

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

이 같은?

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) 

데모 :

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

나는 이것을 편집하여'America *'와'Australia *'라는 2 개의 단어를 추가 할 수 있습니까? – user1315906

+0

네, 다음과 같이 할 수 있습니다 :'re.search (("America * | Australia *)", word)' – Bryan

관련 문제