关于如何改进这种方法的任何想法?
这个想法是继续加入连字符,但在它们单独存在时将其删除。示例输出显示
def de_punctuate(xs):
reg = re.findall(r"[\w'-]+", xs)
#the pupose of `fun` is to only remove any hyphens that stand alone.
#i want to keep hyphens-as-joining
fun = functools.partial(operator.ne, '-')
return filter(fun, reg)
def no_numbers(xs):
isa = functools.partial(operator.contains, string.digits)
fn = lambda x: ''.join(itertools.filterfalse(isa, x))
return list(filter(fn, xs))
for d in data:
print(d)
print(no_numbers(de_punctuate(d)))
输出示例:
Turistguide fikk 40.000 kroner i bot for smugling
['Turistguide', 'fikk', 'kroner', 'i', 'bot', 'for', 'smugling']
- Må kalles opp etter Dale Oen
['Må', 'kalles', 'opp', 'etter', 'Dale', 'Oen']
Kvinne skadet i MC-ulykke ved Haugastøl
['Kvinne', 'skadet', 'i', 'MC-ulykke', 'ved', 'Haugastøl']
输出是我想要的。但我觉得改进的正则表达式会有所帮助!
我认为这看起来有点干净:
def de_punctuate(xs):
return re.findall(r"[\w']+(?:-[\w']+)*", xs)
def no_numbers(xs):
return [ x for x in xs if not re.search(r'[0-9]', x) ]