簡體   English   中英

python的正則表達式更改一組字符

[英]regex for python to change a set of char

我有一個帶有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. 在剪裁尾隨空格( [:-1] )並添加換行符( +\\n )之后,lambda函數用其自身替換匹配的組( m.groups()[0] )。

可能有一種更簡單的方法,該方法不涉及使用組...但這是可行的!

這是因為它正在查找“”的每個實例,然后在其后放置新行。 您可能需要重寫循環以找到更具體的示例。

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

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


print(rawFileString)

從這里您可以換行,並將此字符串寫入新文件等。

注意:這將起作用,因為文本文件中有一個模式。 如果您有更復雜的內容,則可能需要對文本進行多次替換或其他修改才能檢索所需的結果。

編輯:盡管此方法可能會變得凌亂,但您可以避免使用非常復雜的正則表達式,並從定界符的find實例的索引創建子字符串。

您的文件看起來有圖案的方式可能對您有用:

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()

還有一種解決方法,通過考慮以下事實:換行插入始終是“ character”,后跟字母字符的情況。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM