【问题标题】:split string with condition [duplicate]使用条件拆分字符串[重复]
【发布时间】:2017-06-30 14:03:59
【问题描述】:

我正在尝试使用 Python 解析我的 csv 文件。每行有四个以逗号分隔的元素。每个元素都是一个字符串,但它也可以包含逗号。如果元素包含逗号,则该元素被双引号引起来。以下示例显示了带引号和不带引号的两种不同情况:

http://data.europa.eu/esco/skill/CTC_43028,"use data extraction, transformation and loading tools","ETL|extract, transform, load","<div>Integrate information from multiple applications, created and maintained by various organisations, into one consistent and transparent data structure.</div>"
http://data.europa.eu/esco/skill/SCG.TS.1.4.m.2,support company plan,follow industry guidelines|follow organisation's vision|monitor policy implementation|support company mission,<div>Act within one&#39;s work role to advance the goals and vision of the organisation.</div>

我想要的是把每一行分成四个元素。 我尝试过使用 Python 的拆分功能,但没有成功。我想我必须使用正则表达式,但我不熟悉它。 你能帮忙吗? 非常感谢。

【问题讨论】:

  • csv 模块呢?它是为此量身定做的。删除正则表达式...

标签: python regex


【解决方案1】:

csv 模块就是你想要的:

import csv

with open('file.csv') as f:
    r = csv.reader(f)
    for row in r:
        print row

['http...', 'transformation ...', 'ETL|ext ...', '<div>Integrate ...']
['http:...', 'support ...', 'follow ...', '<div>Act ...']

',' 是默认分隔符,'"' 是默认引号字符。

【讨论】:

  • 但是现在每个部分都被引用了,我需要在单个 qoutes 中获取字符串。再次正则表达式?
  • 不,它们没有被引用。单引号只是字符串的repr() 表示的一部分,liststr() 用于显示它们。如果您要单独打印每一行中的字符串,您将看不到引号。
猜你喜欢
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多