![](/img/trans.png)
[英]I have 3 lines in a `.txt` file each line containing 3 numbers and I want to `+1` to them numbers depending on the user input
[英]I have a large Chinese text file and I want to reformat it into individual lines, each ending with a period
我想將此文件分成幾行(每行以一個句點(問號,感嘆號等)結尾),以便以后使用時更容易。
我嘗試使用nltk,但無濟於事:
text = r'你在哪里? 我想看到你的狗!我很喜歡你。'
tokenized_text=sent_tokenize(text)
print(tokenized_text)
實際結果: ['你在哪里? 我想看到你的狗!我很喜歡你。']
預期結果:
['你在哪里? 我想看到你的狗! 我很喜歡你。']
看到沒人回應...
import re
text = r'你在哪里? 我想看到你的狗!我很喜歡你。'
text_tokens = re.findall(r'(.*?[?!。])\s?', text) #with all the seperating tokens between []
print("\n".join(text_tokens))
輸出
你在哪里?
我想看到你的狗!
我很喜歡你。
解釋.+?
尋找一個到無窮大的字符,直到第一個出現的[?!。]
您想在(previous)\\s?
上分割的任何標記(previous)\\s?
如果存在多余的空間,則將其刪除。 通過僅捕獲文本和令牌
"\\n".join(text_tokens)
將列表連接到換行符/將每個匹配項設置為新行。
如果您正在將其從一個文件讀取到另一個文件,那么一個非常簡單的程序可能看起來像這樣
import re
text_tokens = []
with open("example.txt", 'r') as text:
text_tokens = re.findall(r'(.+?[?!。])\s?', text.read())
with open("output.txt", 'w+') as out:
out.write("\n".join(text_tokens))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.