首页 文章

带有转义,引号和分隔符的Python正则表达式

提问于
浏览
2

我是python的新手并尝试使用正则表达式或使用CSV阅读器解决下面的问题 .

我的输入字符串采用以下格式:

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

预期产出是:

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

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

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阅读器或任何带有正则表达式的解决方案的帮助都会很棒 . 谢谢 .

1 回答

  • 1

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

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

相关问题