gpt4 book ai didi

python - python 的正则表达式更改一组字符

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:42 24 4
gpt4 key购买 nike

我有一个 Unicode 字符的文件,其模式如

a unicode string1 । b unicode string2 ॥ १ ॥ c unicode string3 । d unicode string4 ॥ २ ॥

此处 '१'、'२' 不响应数字查询,因为它们是 Unicode 字符。 '॥'之间有空格和'२'。

现在没有换行符,没有中断。我想在每个备用'॥'之后换行所以我可以有这样的模式

a unicode string1 । b unicode string2 ॥ १ ॥ 
c unicode string3 । d unicode string4 ॥ २ ॥

我尝试了一些正则表达式,但由于我对正则表达式的了解不足,无法实现。我的代码示例是,在下面的每个“॥”之后提供一个换行符。

import csv

txt_file = "/path/to/file/file_name.txt"
csv_file = "mycsv.csv"

regex = "॥"

with open(txt_file,'r+') as fr, open('vc','r+') as fw:
for line in fr:
fw.write(line.replace(regex, "॥\n"))

它给出的结果是

a unicode string1 । b unicode string2 ॥ 
१ ॥
c unicode string3 । d unicode string4 ॥
२ ॥

最佳答案

欢迎来到令人困惑的正则表达式世界......

我建议使用 re图书馆,它可以轻松处理你想做的事情。例如:

import re

text = "a unicode string1 । b unicode string2 ॥ १ ॥ c unicode string3 । d unicode string4 ॥ २ ॥"

pattern = '(॥ .{1} ॥ )'

new = re.sub(pattern,
lambda m: m.groups()[0][:-1] + '\n',
text)
print(new)

>> a unicode string1 । b unicode string2 ॥ १ ॥
c unicode string3 । d unicode string4 ॥ २ ॥

一些解释:

  1. pattern 是定义 '॥ [任何字符] ॥'您要在其后放置换行符的模式。 .{1} 表示“任何单个字符”,我在添加 \n 的第二个 后留了一个空格 空格之后,它不会停留在下一行的开头。整个模式放在方括号中,将其标识为单个正则表达式“组”。
  2. 此模式用于 re.sub,它会替换给定字符串中的所有实例。在这种情况下,您想将其替换为原来的内容,外加一个换行符。这发生在 lambda 函数中。
  3. lambda 函数在删除尾随空格 ([:-1]) 后用自身替换匹配的组 (m.groups()[0]) , 并添加换行符 (+\n)

可能有一种不涉及使用组的更简单的方法...但这行得通!

关于python - python 的正则表达式更改一组字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com