【发布时间】:2015-03-16 12:57:05
【问题描述】:
我正在使用的代码:
import urllib2
import csv
from bs4 import BeautifulSoup
url = "http://en.wikipedia.org/wiki/List_of_ongoing_armed_conflicts"
soup = BeautifulSoup(urllib2.urlopen(url))
fl = open('locations.csv', 'w')
def unique(countries):
seen = set()
for country in countries:
l = country.lower()
if l in seen:
continue
seen.add(l)
yield country
locs = []
for row in soup.select('table.wikitable tr'):
cells = row.find_all('td')
if cells:
for location in cells[3].find_all(text=True):
locs.extend(location.split())
locs2 = []
for locations in unique(locs):
locations = locs2.extend(locations.split())
print sorted(locs2)
writer = csv.writer(fl)
writer.writerow(['location'])
for values in sorted(locs2):
writer.writerow(values)
fl.close()
当我打印我正在编写的代码时,我会在每个元素前面看到一个u',我认为这就是它以这种方式输出的原因。我尝试使用.strip(u''),但它给了我一个错误,.strip 不能使用,因为它是一个列表。
我做错了什么?
【问题讨论】:
-
u''是 Python 告诉您字符串是 Unicode 格式的方式。它实际上不是字符串的一部分,所以strip()无论如何都不会删除它。