如何在python csv阅读器中为quotechar使用多个不同的字符
我试图读取一个CSV文件,该文件有时对字符串使用双引号(“),有时对字符串使用单引号(”) 我想读取该文件以正确处理这些字符串如何在python csv阅读器中为quotechar使用多个不同的字符,python,csv,Python,Csv,我试图读取一个CSV文件,该文件有时对字符串使用双引号(“),有时对字符串使用单引号(”) 我想读取该文件以正确处理这些字符串 这是不必要的,但如果正确解析了“don't”,它会很有帮助。这就是为什么我不想只替换每个“for”。处理这一问题的粗略方法是使用regex来检测任何前面有空格或后面有空格的单引号 然后,我们可以用“替换这些引用,而忽略它们旁边有字母的引用 CSV """Let's do a test""","&qu
这是不必要的,但如果正确解析了“don't”,它会很有帮助。这就是为什么我不想只替换每个“for”。处理这一问题的粗略方法是使用
regex
来检测任何前面有空格或后面有空格的单引号
然后,我们可以用“
替换这些引用,而忽略它们旁边有字母的引用
CSV
"""Let's do a test""","""We will replace all 'single' quotation's not within""","""A word to """""
Python
import re
pattern = r'((?<=\s)\')|(\'(?=\s))'
data = []
with open('hello.csv', 'r') as file:
for row in file.readlines():
data.append(re.sub(pattern, '"', row))
您可以使用
quoting=csv.QUOTE\u NONE
阻止csv.reader
处理报价,然后使用ast.literal\u eval
将值解释为Python文本(或者,如果失败,将其保留为字符串)
请注意,由于它们是作为Python文本计算的,因此表示有效Python文本的任何未加引号的字段值(例如True
或42
)将不会保留为字符串
import io
import csv
from ast import literal_eval
def unquote(item):
item = item.strip()
try:
return literal_eval(item.strip())
except ValueError:
return item
f = io.StringIO(r'''
bare, "John \"O'Brien\" Smith", 'John "O\'Brien" Smith', 42
'''.strip())
reader = csv.reader(f, quoting=csv.QUOTE_NONE)
for row in reader:
parsed_row = [unquote(item) for item in row]
print(parsed_row)
# => ['bare', 'John "O\'Brien" Smith', 'John "O\'Brien" Smith', 42]
import io
import csv
from ast import literal_eval
def unquote(item):
item = item.strip()
try:
return literal_eval(item.strip())
except ValueError:
return item
f = io.StringIO(r'''
bare, "John \"O'Brien\" Smith", 'John "O\'Brien" Smith', 42
'''.strip())
reader = csv.reader(f, quoting=csv.QUOTE_NONE)
for row in reader:
parsed_row = [unquote(item) for item in row]
print(parsed_row)
# => ['bare', 'John "O\'Brien" Smith', 'John "O\'Brien" Smith', 42]