【问题标题】:Remove New Line Feed But Only Between Quotes删除新的换行符,但仅在引号之间
【发布时间】:2021-10-14 02:26:58
【问题描述】:

我有以下代码:

output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
output_data = output.content

type(output_date)
<class 'bytes'>

output_data

压缩文本(3632 行)

查看压缩后的文本时,我有一些看起来像这样的值:

Steve likes to walk his dog. Steve says to John "I like \n Pineapple, oranges, \n and pizza.\n" and then he went to bed \n.
John likes his beer cold.\n
Sally likes her teeth brushed with a bottle of jack.\n

如何删除 \n 字符,但前提是它包含在双引号内,以便我的结果如下所示:

Steve likes to walk his dog. Steve says to John "I like Pineapple, oranges, and pizza." and then he went to bed \n.
John likes his beer cold.\n
Sally likes her teeth brushed with a bottle of jack.\n

我知道如何删除 \n 字符,但如果我只想删除包含在双引号中的值,我不确定如何执行此操作。

这是我尝试过的:

我找到了this,并使用了这个代码:

my_text = re.sub(r'"\\n"','',my_text)

但它似乎不起作用。

【问题讨论】:

  • '"\\n"' 您的文本不包含直接用双引号括起来的换行符。
  • 你能澄清一下吗?我不明白。
  • re.sub(r'"\\n"','',my_text) 这不起作用,因为它会查找双引号的精确模式,然后是换行符,然后是双引号。您的文本不包含该模式——它在双引号和换行符之间有多余的字符。

标签: python python-3.x newline


【解决方案1】:

我可能有点复杂,但这样的事情可能会奏效

parts = content.split("\"")
for i, part in enumerate(parts):
    if i % 2:
        parts[i] = part.replace("\n", "")
content = "\"".join(parts)

【讨论】:

  • 这其实是一个非常好的方法。解析器或多或少会做什么,计算引号并定义交替输入/输出组。
【解决方案2】:

想通了。

步骤:

  1. 将字节转换为字符串
  2. 为正则表达式创建模式
  3. 使用正则表达式格式化值。

第 1 步:

my_text = my_text.decode("utf-8")

第 2 步:

pattern = re.compile(r'".*?"',re.DOTALL)

第 3 步:

my_text = pattern.sub(lambda x:x.group().replace('\n',''),my_text)

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多