【问题标题】:When writing to a csv file, why is each letter in a column?写入 csv 文件时,为什么每个字母都在一列中?
【发布时间】: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() 无论如何都不会删除它。

标签: python csv unicode


【解决方案1】:

locs2 是一个包含字符串的列表,而不是一个列表列表。因此,您正在尝试将单个字符串写成一行:

for values in sorted(locs2):
    writer.writerow(values)

这里values是一个字符串,writerow()把它当作一个序列。您传递给该函数的任何序列的每个元素都将被视为单独的列。

如果您想将所有位置写为 一个 行,请将整个列表传递给 writer.writerow()

writer.writerow(sorted(locs2))

如果您想为每个单独的位置写一个新行,请先将其包装在一个列表中:

for location in sorted(locs2):
    writer.writerow([location])

您不需要将字符串中的u 前缀串起来;这只是 Python 告诉你有 Unicode 字符串对象,而不是字节字符串对象:

>>> 'ASCII byte string'
'ASCII byte string'
>>> 'ASCII unicode string'.decode('ascii')
u'ASCII unicode string'

如果您想了解有关 Python 和 Unicode 的更多信息,请参阅以下信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2015-10-23
    • 2018-02-04
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多