我在 Python 中有一個大文本檔案。我想為每個句子換行。對于每一行應該只包含一個句子資訊。
例如:
輸入:
The Mona Lisa is a half-length portrait painting by Italian artist Leonardo da Vinci. Considered an archetypal masterpiece of the Italian Renaissance, it has been described as "the best known, the most visited, the most written about, the most sung about, the most parodied work of art in the world". Numerous attempts in the 21. century to settle the debate.
輸出:
The Mona Lisa is a half-length portrait painting by Italian artist Leonardo da Vinci.
Considered an archetypal masterpiece of the Italian Renaissance, it has been described as "the best known, the most visited, the most written about, the most sung about, the most parodied work of art in the world".
Numerous attempts in the 21. century to settle the debate.
我試過了 :
with open("new_all_data.txt", 'r') as text, open("new_all_data2.txt", "w") as new_text2:
text_lines = text.readlines()
for line in text_lines:
if "." in line:
new_lines = line.replace(".", ".\n")
new_text2.write(new_lines)
它為句子換行;但是,它會為“.”之后的每個字串創建一個新行。
例如:
The Mona Lisa is a half-length portrait painting by Italian artist Leonardo da Vinci.
Considered an archetypal masterpiece of the Italian Renaissance, it has been described as "the best known, the most visited, the most written about, the most sung about, the most parodied work of art in the world".
Numerous attempts in the 21.
century to settle the debate.
我想將“在 21 世紀為解決這場辯論進行的無數次嘗試”保持一致。
uj5u.com熱心網友回復:
您只需替換句點后跟一個空格和一個大寫字母:
import re
with open("new_all_data.txt", 'r') as text, open("new_all_data2.txt", "w") as new_text2:
text_lines = text.readlines()
for line in text_lines:
if "." in line:
new_lines = re.sub(
r"(?<=\.) (?=[A-Z])",
"\n",
line
)
new_text2.write(new_lines)
我使用re允許使用函式執行基于正則運算式的替換的模塊re.sub。然后,在該行中,我搜索與以下正則運算式匹配的空格:(?<=\.) (?=[A-Z])
- 空格之前必須有句點。我用
(?<=xxx)which is a positive look behind,它確保比賽xxx剛剛過去)。\.匹配一個句點,所以(?<=\.)(注意最后的空格)確保我匹配在它之前有句點的空格。 - 空格后面必須有一個大寫字母。我使用
(?=xxx)which 是一個積極的展望,它確保比賽xxx緊隨其后)。[A-Z]匹配任何大寫字母,因此(?=[A-Z])(注意開頭的空格)確保我匹配后面有大寫字母的空格。
結合這兩個條件應該足以用新行替換兩個句子之間的空格。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527600.html
