【问题标题】:Python not recognizing quotesPython不识别引号
【发布时间】:2017-12-17 15:11:13
【问题描述】:

我想做的事情非常简单。

  1. 从文件中检索文本
  2. 如果文本包含引号,则获取引号内的文本。

为此,我正在使用从另一篇文章借来的这个正则表达式。

re.findall('"([^"]*)"', text)

我遇到的问题是,我的文本文件中包含的特定引号没有被识别为引号。

例如:

text = #get text from a file

print(text) 
#Outputs: 'this is a "test"'

print(re.findall('"([^"]*)"', text))
#Outputs: []

但是,如果我直接将字符串作为变量输入,它会正常工作。

text = 'this is a "test"'

#The same regex outputs ['test']

所以我相信我的问题与编码有关。话虽如此,type(text) 返回 str。

编辑:感谢@rmharrison,我找到了解决方案 这是现在的工作

import re
from unidecode import unidecode

text = # Text From File

cleaned_text = unidecode(text)

print(re.findall('"([^"]*)"', cleaned_text))

#This successfully outputs text inside quotes. 

【问题讨论】:

  • 也许你在使用花引号
  • 你使用的是 Python2 还是 Python3?而且,print(repr(text)) 透露了什么?
  • 请提供一个简短的可重现测试用例。请参阅 minimal reproducible example 了解原因和方法。
  • 我正在使用 python 3 并且 print(repr(text)) 显示'这是一个“测试”'
  • 我搞定了。见上面的编辑

标签: python regex string encoding quotes


【解决方案1】:

感谢@rmharrison,我找到了解决方案 这是现在的工作

import re
from unidecode import unidecode

text = # Text From File

cleaned_text = unidecode(text)

print(re.findall('"([^"]*)"', cleaned_text))

#This successfully outputs text inside quotes. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多