用于python的正则表达式来更改一组char

时间:2017-04-05 03:16:43

标签: python regex unicode

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

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

这里'1','2'这些都没有响应数字查询,因为它们是Unicode字符。 '。'之间有空格。和'2'。

现在没有新行,没有休息。我希望在每个候补''之后都有换行符。所以我可以有像

这样的模式
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 ॥ 
२ ॥

3 个答案:

答案 0 :(得分:2)

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

我建议使用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添加之后 em>空间,并且它不会在下一行的开头处闲逛。整个模式放在括号中,将其标识为单个正则表达式'。
  2. 此模式用于re.sub,它替换给定字符串中的所有实例。在这种情况下,您希望将其替换为原来的内容以及换行标记。这发生在lambda函数中。
  3. lambda函数在修剪尾随空格(m.groups()[0])后添加换行符([:-1]
  4. 后,将匹配的组替换为自身(+\n

    可能有一种更简单的方法可以做到这一点并不涉及使用群组......但是这有效!

答案 1 :(得分:1)

这是因为它正在查找"的每个实例。 。 "然后在它之后添加一个新行。您可能想要重写循环以找到更具体的示例。

regex = '॥ १ ॥'
txt_file = open("newTextFile.txt", "r")

rawFileString=txt_file.read()
rawFileString=rawFileString.replace(regex,'॥ १ ॥\n')


print(rawFileString)

从这里你可以获得新行,并将此字符串写入新文件等。

注意:这将起作用,因为文本文件中有一个模式。如果您有更复杂的事情,可能需要对文本进行多次替换或其他修改以检索所需的结果。

编辑: 虽然这种方法可能会变得混乱,但您可以避免使用非常复杂的正则表达式,并从分隔符的查找实例的索引创建子字符串。

您的文件的图案形式可能对您有用:

txt_file = open("newTextFile.txt", "r")

rawFileString=txt_file.read()


startOfText = 0
delimiter = '॥'


instance1= rawFileString.find(delimiter)
#print rawFileString.find(delimiter)

instance2= rawFileString.find(delimiter, instance1+1)
#print rawFileString.find(delimiter,instance1+1)

counter=0  

#for this while loop you may want to change 10 to be the number of lines in the document multiplied by 2.

while counter<10:
        substring=rawFileString[startOfText:instance2+3]  
        print(substring)
        startOfText = instance2+4 
        instance1 = rawFileString.find(delimiter, startOfText)
        instance2 = rawFileString.find(delimiter, instance1+1)
        counter=counter+1
txt_file.close()

答案 2 :(得分:1)

还有另一种方法可以解决,通过考虑“。”这一事实,后面跟一个字母字符始终是新行插入的情况。

s = r'unicode string1 । b unicode string2 ॥ १ ॥ c unicode string3 । d unicode string4 ॥ २ ॥'
occurrences = re.split(r'॥ [a-z]{1,}', s)
for item in occurrences[:-1]:
        print item.strip()+" ॥"
print occurrences[:-1].strip()