使用sed或我可以在txt文件的目录上运行的其他程序,如何从文件中删除纯数字以及数字和字母的组合,除那些属于法国基数(例如2ème)的部分。自动删除包含“ème”的数字和字母数字文字
例如,如果一个文本文件包含
12h03 11:00 27.8.16 23 3ème bonjour
然后我只想留住
3ème bonjour
编辑:因为没有号码出现在它卓悦被保留。 3ème保留,因为它结束于ème(基数)。其他令牌被删除,因为它们包含数字,但不是基数。
使用sed或我可以在txt文件的目录上运行的其他程序,如何从文件中删除纯数字以及数字和字母的组合,除那些属于法国基数(例如2ème)的部分。自动删除包含“ème”的数字和字母数字文字
例如,如果一个文本文件包含
12h03 11:00 27.8.16 23 3ème bonjour
然后我只想留住
3ème bonjour
编辑:因为没有号码出现在它卓悦被保留。 3ème保留,因为它结束于ème(基数)。其他令牌被删除,因为它们包含数字,但不是基数。
jwpfox:我从来没有用过Python,但我愿意使用它。
与此同时,我写了一个猪丑陋的R
脚本,似乎足以达到我的目的。我会在这里分享。
# Sample text
text <- "Le 8 septembre à 11h30, Jean voyait les 2 filles pour la 3ème fois."
# Split up by space
splittext <- unlist(strsplit(text,
split = " "))
# Retain words containing no numbers, or that contain 'ème' or punctuation.
selecttext <- splittext[!(grepl("\\d", splittext)) |
grepl("ème", splittext) |
grepl("[[:punct:]]", splittext)]
# If a word contains both numbers and punctuation, retain only the punctuation
selecttext[grepl("\\d", selecttext) & grepl("[[:punct:]]", selecttext)] <- stringr::str_sub(selecttext[grepl("\\d", selecttext) & grepl("[[:punct:]]", selecttext)], start=-1, end =-1)
# Recombine
text2 <- paste(selecttext, collapse = " ")
> text2
[1] "Le septembre à , Jean voyait les filles pour la 3ème fois."
它应该是读取目录中的所有文件,通过上面的行运行它们,并覆盖源文件。
既然你打开一个Python的答案,这里是Python3中的一个。
在filepath
变量中提供要在其中工作的树的根目录的路径,这将遍历该目录下树中的所有文件并应用您提供的规则。
请注意,您似乎在您的R
代码中应用的规则似乎与您在问题中提出的规则不同。
import os
import re
filepath = 'testfiles'
for(path, dirs, files) in os.walk(filepath):
searchpattern = re.compile('[0-9]')
for filename in files:
curfilepath = os.path.join(path, filename)
with open(curfilepath, mode='r', encoding='utf-8') as infile:
cleanlines = []
for line in infile:
cleanline = ''
words = line.split(' ')
for word in words:
if 'ème' in word:
cleanline += word + ' '
if searchpattern.search(word) is None:
cleanline += word + ' '
cleanline = cleanline.strip()
if len(cleanline) > 0:
cleanlines.append(cleanline)
with open(curfilepath, mode='w', encoding='utf-8') as outfile:
for line in cleanlines:
outfile.write(line + '\n')
实际的规则是什么?你说你只想要包含'ème'的单词,然后在你的例子中包含bonjour作为保留的东西。规则集的哪一部分允许“bonjour”被包含在输出中? – jwpfox
抱歉不清楚:如果有数字出现,应删除单词,除非以'ème'结尾。 –
所以这条线“那么我只想保留'3èmebonjour'。”应该阅读“那么我只想保留'3èmer'。”是对的吗? – jwpfox