2015-01-28 2 views
0

문자열을 구문 분석하려고하는데 특정 단어를 추출하려고합니다.큰 문자열을 파이썬으로 구문 분석

문자열 SEE ALSO 섹션에서

{{About|the ALGOL-like programming language|the scripting language formerly named Small|Pawn (scripting language)}} 

'''SMALL''', Small Machine Algol Like Language, is a [[computer programming|programming]] [[programming language|language]] developed by Dr. [[Nevil Brownlee]] of [[Auckland University]]. 

==History== 
The aim of the language was to enable people to write [[ALGOL]]-like code that ran on a small machine. It also included the '''string''' type for easier text manipulation. 

SMALL was used extensively from about 1980 to 1985 at [[Auckland University]] as a programming teaching aid, and for some internal projects. Originally written to run on a [[Burroughs Corporation]] B6700 [[Main frame]] in [[Fortran]] IV, subsequently rewritten in SMALL and ported to a DEC [[PDP-10]] Architecture (on the [[Operating System]] [[TOPS-10]]) and IBM S360 Architecture (on the Operating System VM/[[Conversational Monitor System|CMS]]). 

About 1985, SMALL had some [[Object-oriented programming|object-oriented]] features added to handle structures (that were missing from the early language), and to formalise file manipulation operations. 

==See also== 
*[[ALGOL]] 
*[[Lua (programming language)]] 
*[[Squirrel (programming language)]] 

==References== 
*[http://www.caida.org/home/seniorstaff/nevil.xml Nevil Brownlee] 

[[Category:Algol programming language family]] 
[[Category:Systems programming languages]] 
[[Category:Procedural programming languages]] 
[[Category:Object-oriented programming languages]] 
[[Category:Programming languages created in the 1980s]] 


내가 ALGOL, 루아 (프로그래밍 언어), 다람쥐 (프로그래밍 언어)를 추출합니다. (정확하게이 단어는 괄호 또는 별표를 추가하지 않습니다.)
나는이 접근법을 시도했습니다
문자열 분할, 정규식. 아직 아무데도, 도움말 감사합니다. 나에 의해 사용



코드

import urllib.request,json,re 

url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=SMALL&prop=revisions&rvprop=content" 
response = urllib.request.urlopen(url) 
str_response = response.readall().decode('utf-8') 
obj = json.loads(str_response) 
a=str(obj['query']['pages']['1808130']['revisions'][0]['*']) 
print(a) 

문자열이 저장됩니다.

+0

* 정확하게 * 시도 했습니까? 문자열을 줄로 나눌 수 있고'== See Also =='와 다음 섹션 (또는 파일 끝) 사이의 모든 줄을 추출한 다음 모든 줄에 적합한 정규 표현식을 적용 할 수 있습니다. –

+0

그건 json이 아니에요. 어떻게 그렇게 할 수 있죠? –

+0

@FrerichRaabe 님이 어떻게 모든 줄을 추출 할 것을 제안합니까 == 참고 == 및 다음 섹션? 정규식을 사용하여 ?? 중간에 줄을위한 정규 표현식을 썼습니다. 즉 "\ W \ W \ W [a-z, A-Z \ W] + \ W \ W" –

답변

0

내가 올바르게 이해하면 과 ==References== 사이의 문자가 필요합니다 (이 중 *[] 제외). 초기 문자열을 my_string으로 지정했습니다.

import re 

# Sliced_string will only contain the characters between '==See also==' and '==References==' 
sliced_string = re.findall(r'==See also==(.*?)==References==', my_string, re.DOTALL)[-1] 

# Removes stars and brackets 
for unwanted_char in '[]*': 
    sliced_string = sliced_string.replace(unwanted_char, '') 

# Creates a list of strings (also removes empty strings) 
final_list = sliced_string.split('\n') 
final_list = [elem for elem in final_list if elem != ''] 

print(final_list) 

편집 : 목록에 변환 된 문자열입니다.

주어진 문자열에 ==See also====References==이 하나만 있다고 가정하면 코드가 올바르게 작동합니다.

+0

작업을 완벽하게 수행 ... 적용한 정규 표현식을 설명해 주시겠습니까? 복잡한 정규 표현식에 익숙하지 않다. –

+0

첫째,'something '대신에'r'something'와 같은 원시 문자열을 사용해야한다. 이제 정규식에 관해서; 괄호는'findall'이 반환 할 일치 부분을 나타냅니다 (전체 패턴과 일치하지만 괄호 내용 만 반환합니다). 점 '.'는 새 줄을 제외한 _ 문자를 의미합니다 ._ 're.DOTALL'을 플래그로 사용하면 새로운 행과도 일치합니다. 별'*'은 _from 0에서 무한 문자 _까지를 의미합니다. '*?'이면 '== References =='에 도달하기 전에 가능한 한 일치하지 않게됩니다. –

+0

자세한 내용은 https://docs.python.org/3/library/re.html에서 확인하거나 문의하십시오. –

1
print re.findall(r"\*\[\[([^\]]*)\]\]",re.findall(r"==See also==((?:\s+\*\[\[(?:[^\]]*)\]\])+)",x)[0]) 

x를 직접 입력하고 x에 저장된 문자열을 보내십시오.