更高效的正则表达式

问题描述 投票:0回答:1

我正在解析大约20万份文档(每份约1-3gb),以使用regex删除所有非字母数字字符,并匹配一些古老代码的输入格式。每个单词编号需要用一个 _.

我已经把它们分成了不同的部分,所以它可以工作,但我一直试图把这些表达式组合成一个,但没有成功。

请问如何将这几部分组合在一起?

组合成表达式有什么注意事项?

def clean_document(raw_input):
    no_more_etf = re.sub(r'[^\x00-\x7F]+', '', raw_input)
    no_more_non_utf = re.sub(r'[\000-\011\013-\037]', '', no_more_etf)
    no_more_spaces = re.sub('\s+', '_', no_more_non_utf.strip())
    almost_there = re.sub('[^0-9a-zA-Z]+', '_', no_more_spaces)
    clean_string = almost_there.lower()
    return clean_string

示例字符串。'"where is the Vehicles 我是一群隨機人物 "countries"=>"35,214" "refinement"=>"3" 我的书在哪里"I\'m a dirty array object"=>"" "category_ids"=>"2,5,7,8" "data_size_units"=>"", "delivery_formats"=>"1,4" "delivery_® ® ®methods"=>"1,2", "price_currencies"=>"1" , "trial_currencies"=>"1", "categories"=>"2,10 ,19", "Delivery_growth_units ® ® ®"=>"", "trial_duration_units"=>"6", 私の本はどこですか "collection_time_units"=>"", "strategies"=>"2,3 , 4,6", "processing_time_units"=>"", "delivery_frequency_units" =>"", "subscription_duration_units "=>"6" ® ® ® ģ ģ ģ - GPS Place-Visits for Delivery Vehicles'

python regex re
1个回答
1
投票

你可以使用标准字符串的 translate 方法来执行所有这些替换(除了 .strip())(参见 string.translate 和 string.maketrans)。https:/docs.python.org2librarystring.html。 ).

如果你不想使用 translate,你可以在函数外准备编译版本的替换模式,并在 re.sub() 调用中使用编译版本。 另外,使用一个re.sub()而不是多个re.sub()也会让事情变得更快。

© www.soinside.com 2019 - 2024. All rights reserved.