简体   繁体   English

用双引号转义双引号

[英]Escape a double quote with a double quote

I'm trying to get csv writer to use a double quote as an escape character and add a double quote to a double quote if it appears in the data field.我试图让 csv 编写器使用双引号作为转义字符,如果双引号出现在数据字段中,则将双引号添加到双引号中。

My function is part of an Apache Beam Dataflow job.我的 function 是 Apache Beam 数据流作业的一部分。

Any advice would be appreciated.任何意见,将不胜感激。

The input record: "ab"c","def"输入记录:"ab"c","def"

The actual output my function returns: abc", def实际 output 我的 function 返回:abc", def

The output I'm trying to achieve "abc""", def output 我正在尝试实现“abc”“”,def

The input file may contain records like this:输入文件可能包含如下记录:

1, "mystring1","mystring2" 1、“我的字符串1”、“我的字符串2”
2, "mystring3","mystring4" 2、“我的字符串3”、“我的字符串4”
3, "myst"ring5","mystring6" 3, "myst"ring5","mystring6"

Notice record 3 has a double quote in the field.通知记录 3 在字段中有双引号。

I would like to escape that double quote by adding我想通过添加来逃避双引号
a double quote before it then quote the entire field.在它之前加一个双引号,然后引用整个字段。

1, mystring1,mystring2 1,我的字符串1,我的字符串2
2, mystring3,mystring4 2、我的字符串3、我的字符串4
3, "myst""ring5",mystring6 3, "myst""ring5",mystring6

The function I'm calling function 我打电话

def parse_file(element):
      for line in csv.reader([element], quotechar='"', delimiter=','):
          output_str = io.StringIO()
          cw = csv.writer(output_str, quotechar='"', delimiter=',', escapechar='"', quoting=csv.QUOTE_MINIMAL)
          cw.writerow(line)
          output_str.close()
          clean_line = ', '.join(line)
          return clean_line

Here is a simple solution which takes the input element of type string.这是一个简单的解决方案,它采用字符串类型的输入元素。

vec = str('"ab"c","def""')
print(list(map(lambda x: '"' + x + '"' if '""' in x else x, [y.strip('"').replace('"', '""') for y in vec.split(',')])))

If i understood something wong I apologies如果我明白了什么,我很抱歉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM