关于如何改进此方法的任何想法?
想法是保留连字符,但当它们独立时将其删除。
显示了示例输出
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) ]
最佳答案
尝试这样的事情:
re.findall(r"[\w']+(?:-[\w']+)*", myString)
对于
myString = "walk-the-dog can - i - --have -- a- -- look at your pocket-book?"
这样产生:
['walk-the-dog', 'can', 'i', 'have', 'a', 'look', 'at', 'your', 'pocket-book']
关于python - 更好地使用re以避免两次通过,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11479871/