【发布时间】:2019-03-13 19:08:46
【问题描述】:
我有一段法语文本,其中包含用空格分隔的单词(例如 répu blique*)。我想从文本中删除这些分隔的单词并将它们附加到列表中,同时在文本中保留标点符号和数字。我的代码适用于附加分开的单词,但不能保留文本中的数字。
import nltk
from nltk.tokenize import word_tokenize
import re
with open ('french_text.txt') as tx:
#opening text containing the separated words
#stores the text with the separated words
text = word_tokenize(tx.read().lower())
with open ('Fr-dictionary.txt') as fr: #opens the dictionary
dic = word_tokenize(fr.read().lower()) #stores the first dictionary
pat=re.compile(r'[.?\-",:]+|\d+')
out_file=open("newtext.txt","w") #defining name of output file
valid_words=[ ] #empty list to append the words checked by the dictionary
invalid_words=[ ] #empty list to append the errors found
for word in text:
reg=pat.findall(word)
if reg is True:
valid_words.append(word)
elif word in dic:
valid_words.append(word)#appending to a list the words checked
else:
invalid_words.append(word) #appending the invalid_words
a=' '.join(valid_words) #converting list into a string
print(a) #print converted list
print(invalid_words) #print errors found
out_file.write(a) #writing the output to a file
out_file.close()
因此,使用此代码,我的错误列表带有数字。
['ments', 'prési', 'répu', 'blique', 'diri', 'geants', '»', 'grand-est', 'elysée', 'emmanuel', 'macron', 'sncf', 'pepy', 'montparnasse', '1er', '2017.', 'geoffroy', 'hasselt', 'afp', 's', 'empare', 'sncf', 'grand-est', '26', 'elysée', 'emmanuel', 'macron', 'sncf', 'saint-dié', 'epinal', '23', '2018', 'etat', 's', 'vosges', '2018']
我认为问题出在正则表达式上。有什么建议么?谢谢!!
【问题讨论】:
-
更容易显示示例文本以及您的正则表达式对它的作用。这更好,因为没有人知道您的文件中有什么或您如何使用它。
-
换句话说,'你的输入是什么,你想要的输出是什么?'
标签: python regex list punctuation