【问题标题】:Using Python to 're.split' unicode characters使用 Python 're.split' unicode 字符
【发布时间】:2013-12-09 22:44:33
【问题描述】:

我正在尝试将以下数据字段拆分为 3 个字段(pre、match 和 suf)并将它们输入到逗号分隔的 txt 文件中。我正在从 csv 文件中读取所有这些内容……它是 utf-8 数据。

我现在的问题是我无法解决“TypeError: coercing to Unicode: need string or buffer, list found”错误......但是,看到我尝试设置我的编码,我没有不知道哪里出了问题……

样本数据:

 A-1 طس
 TX 35-L
 Av Rib

对此进行拆分应该 (\d+(-?[NSEW])?) 提供给我:

Column1 | Column2 | Column3
A       |1        |طس
TX      |35       |-L
Av Rib  |         |

我当前的代码是这样的:

## Iterate over csv file to create matches and splits 
## string according to regex pattern..

    reader = csv.reader(csvfile)

    with codecs.open(r'file.txt', 'w', 'utf-8') as outfile1:
        for row in reader:
           unicode_row = [x.decode('utf-8') for x in row]
           item = unicode_row[1]
           parsed = re.compile("\d+(-?[NSEW])?", re.UNICODE).split(unicode(item, 'utf-8'))
           outfile1.write(parsed + "\n")

【问题讨论】:

  • 你究竟是从哪里得到 TypeError 的? csvfile 是用codecs.open 打开还是只用open 打开?
  • 是 Python3 还是 Python2 的问题?
  • 使用 2.7,我打开 csvfile 以仅使用“打开”进行读取(但您可以看到写入文件正在使用编解码器)。
  • 使用编码并没有多大作用......我得到同样的错误: l = re.compile(ur'(?u)\d+(-?[NSEW])?' , re.UNICODE).split(unicode(item, 'utf-8')) & outfile1.write(u'l' + "\n")

标签: python regex unicode compiler-errors


【解决方案1】:

您的错误是因为parsed 是一个列表列表。

http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2014-07-18
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多