【问题标题】:Python Regular Expression with escape, quote, and delimiter characters带有转义、引号和分隔符的 Python 正则表达式
【发布时间】:2017-08-02 04:26:31
【问题描述】:

我是 python 新手,正在尝试使用正则表达式或 CSV 阅读器解决以下问题。

我的输入字符串格式如下:

"some text"|"sample\" name|place\\""|"some other text\\""

预期输出是:

'some text','sample" name|place\"','some other text\"'

我的字符串有分隔符、转义字符和引号字符。当我将输入文本保存在文件中并使用 csv 阅读器读取时,它按预期工作。

with open('inputfile.csv') as csvfile:
    inputValue = csv.reader(csvfile, delimiter='|', quotechar='"',escapechar = '\\')
    for eachVal in inputValue:
        print(','.join(eachVal))

但是当我将输入值放入列表并使用 CSV 阅读器时,它没有给出正确的输出。

inputText = '"some text"|"sample\" name|place\\""|"some other text\\""'
inputValue = csv.reader(inputText, delimiter='|',quotechar='"', escapechar = '\\')
for eachVal in inputValue:
    print(','.join(eachVal))  

对这个 CSV 阅读器的任何帮助或任何使用正则表达式的解决方案都会很棒。谢谢。

【问题讨论】:

    标签: python regex csv backslash reader


    【解决方案1】:

    当您从文件中读取字符串时,您正在读取“原始”文本,这意味着 Python 不为反斜杠字符等提供特殊处理。要在代码中对字符串文字进行相同处理,您应该为字符串添加前缀 'r'(用于原始)。例如:

    inputText = r'"some text"|"sample\" name|place\\""|"some other text\\""'
    

    【讨论】:

    • 另外,csv.reader() 不需要字符串,而是行上的迭代器。所以请使用inputText.splitlines()StringIO(inputText)
    • @wolfmanx,我在我的代码中使用了 splitlines() 方法,抱歉,这里错过了。
    猜你喜欢
    • 2011-12-15
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2021-12-27
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多