2014-07-11 3 views
0

아래 포럼과 비슷한 게시자를 위해이 포럼을 수색했기 때문에 중복 된 질문이 없기를 바랍니다.Python의 html 태그에서 문자열 추출하기

기본적으로 아래에 표시된 URL에서 각 우주선의 호출 부호를 긁어서 목록에 추가하는 python 스크립트를 만들었습니다. 즉, 목록을 반복하고 각 요소를 표시 할 때마다 각 호출 부호 사이에 '['및 ']'가있는 것처럼 보입니다. 내가 아래에있는 내 스크립트의 출력을 표시했습니다

출력 당신이 볼 수 있듯이

***********************  Contents of 'listOfCallSigns' List  *********************** 

0 ['311062900'] 
1 ['235056239'] 
2 ['305500000'] 
3 ['311063300'] 
4 ['236111791'] 
5 ['245639000'] 
6 ['235077805'] 
7 ['235011590'] 

를, 각 호출 부호의 대괄호를 보여줍니다. 이것이 BeautifulSoup 라이브러리 내의 인코딩 문제에 대한 것일 수 있다고 생각합니다.

이상적으로는 출력에 대괄호가없고 은 호출 부호 만 문자열로 사용하기를 원합니다.

***********************  Contents of 'listOfCallSigns' List  *********************** 

0 311062900 
1 235056239 
2 305500000 
3 311063300 
4 236111791 
5 245639000 
6 235077805 
7 235011590 

내가 현재 사용하고이 스크립트는 다음과 같습니다

내 스크립트

# Importing the modules needed to run the script 
from bs4 import BeautifulSoup 
import urllib2 
import re 
import requests 
import pprint 


# Declaring the url for the port of hull 
url = "http://www.fleetmon.com/en/ports/Port_of_Hull_5898" 


# Opening and reading the contents of the URL using the module 'urlib2' 
# Scanning the entire webpage, finding a <table> tag with the id 'vessels_in_port_table' and finding all <tr> tags 
portOfHull = urllib2.urlopen(url).read() 
soup = BeautifulSoup(portOfHull) 
table = soup.find("table", {'id': 'vessels_in_port_table'}).find_all("tr") 


# Declaring a list to hold the call signs of each ship in the table 
listOfCallSigns = [] 


# For each row in the table, using a regular expression to extract the first 9 numbers from each ship call-sign 
# Adding each extracted call-sign to the 'listOfCallSigns' list 
for i, row in enumerate(table): 
    if i: 
     listOfCallSigns.append(re.findall(r"\d{9}", str(row.find_all('td')[4]))) 


print "\n\n***********************  Contents of 'listOfCallSigns' List  ***********************\n" 

# Printing each element of the 'listOfCallSigns' list 
for i, row in enumerate(listOfCallSigns): 
    print i, row 

사람이 각각의 호출 부호 그냥 디스플레이를 둘러싼 대괄호를 제거하는 방법을 알고 있나요 그 끈?

미리 감사드립니다. :)에

답변

3

변경 마지막 라인 : 또는

# Printing each element of the 'listOfCallSigns' list 
for i, row in enumerate(listOfCallSigns): 
    print i, row[0] # <-- added a [0] here 

, 당신은 또한 여기에 [0] 추가 할 수 있습니다 : 여기

for i, row in enumerate(table): 
    if i: 
     listOfCallSigns.append(re.findall(r"\d{9}", str(row.find_all('td')[4]))[0]) <-- added a [0] here 

설명은 re.findall(...)이 경우에 (목록을 반환한다는 것입니다, 그 안에 하나의 요소가 있음). 그래서, listOfCallSigns는 "하위 목록의 목록을 하나의 문자열을 포함하는 각"될 수있을 테니까요 :

>>> listOfCallSigns 
>>> [ ['311062900'], ['235056239'], ['311063300'], ['236111791'], 
['245639000'], ['305500000'], ['235077805'], ['235011590'] ] 

을 때 listOfCallSigns에서, row 변수는 기본적으로 당신은 왜 당신이 할 수 그건 (코드에서 이전에 추가 된 re.findall(...) 당신의 enumerate 둘 중 하나 뒤에 [0]을 추가하십시오.

그래서 rowre.findall(...) 유형의 모두에게 "문자열 (들)의 목록을"이며, 다음과 같이 :

>>> row 
>>> ['311062900'] 

그리고 목록 내부 문자열을 얻으려면, 당신은 즉, 자사의 첫 번째 요소에 액세스해야합니다 :

>>> row[0] 
>>> '311062900' 

희망이 있습니다.

+0

브릴리언트! 이것은 효과가있다! 저는 매우 흥미가 있습니다. 행 [0]을 삽입하면 대괄호가 제거되는 이유를 설명해 주시겠습니까? 이제 각 목록 요소를 문자열로 반환합니까? – user3560844

+0

목록에서 문자열을 가져 오는 방법에 대한 세부 정보를 추가하기 위해 답을 편집했습니다. – ncocacola

+0

굉장해! 고마워요! – user3560844

0

이은과 같이 문자열에서 원하지 않는 문자를 제거하여 수행 할 수 있습니다 :

a = "string with bad characters []'] in here" 
a = a.translate(None, "[]'") 
print a 
관련 문제