簡體   English   中英

使用正則表達式在Python中拆分句子

[英]Splitting sentences in Python using regex

我正在嘗試從句子中拆分單詞,標點符號和數字。 但是,我的代碼產生了意外的輸出。 我該如何解決?

這是我的輸入文本(在文本文件中):

 "I 2changed to ask then, said that mildes't of men2,

我的代碼輸出如下:

['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men2']

但是,預期的輸出是:

 ['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men','2']

這是我的代碼:

import re
newlist = []
f = open("Inputfile2.txt",'r')
out = f.readlines()
for line in out:
    word = line.strip('\n')
    f.close()
    lst = re.compile(r"\d|\w+[\w']+|\w|[^\w\s]").findall(word)
print(lst)

在正則表達式中,“ \\ w”匹配任何字母數字字符,即[a-zA-Z0-9]。

同樣在正則表達式的第一部分中,它應為'\\ d +'以匹配多個數字。

通過將'+'更改為'*',可以將正則表達式'\\ w + [\\ w'] + | \\ w'的第二部分和第三部分合並為單個部分。

import re
with open('Inputfile2.txt', 'r') as f:
    for line in f:
        word = line.strip('\n')
        lst = re.compile(r"\d+|[a-zA-Z]+[a-zA-Z']*|[^\w\s]").findall(word)
        print(lst)

這給出:

['"', 'I', '2', 'changed', 'to', 'ask', 'then', ',', 'said', 'that', "mildes't", 'of', 'men', '2', ',']

請注意,您的預期輸出不正確。 它缺少一個“,”。

暫無
暫無

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

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