【发布时间】:2013-09-13 09:17:34
【问题描述】:
(免责声明:这是我的第一个 stackoverflow 问题,如果我不太清楚,请提前原谅我)
预期结果:
我的任务是在代表公司名称的字符串中找到公司合法标识符,然后将它们从中分离出来,并将它们保存在单独的字符串中。 公司名称已被清理,因此它们仅包含字母数字小写字符。
例子:
company_1 = 'uber wien abcd gmbh'
company_2 = 'uber wien abcd g m b h'
company_3 = 'uber wien abcd ges mbh'
应该会导致
company_1_name = 'uber wien abcd'
company_1_legal = 'gmbh'
company_2_name = 'uber wien abcd'
company_2_legal = 'gmbh'
company_3_name = 'uber wien abcd'
company_3_legal = 'gesmbh'
我现在在哪里:
我从 csv 文件加载所有公司 ID 的列表。奥地利提供了一个很好的例子。两个合法身份是:
gmbh
gesmbh
我使用一个正则表达式告诉我 IF 公司名称包含合法标识符。但是,此正则表达式会从字符串中删除 所有 个空格以识别合法 id。
company_1_nospace = 'uberwienabcdgmbh'
company_2_nospace = 'uberwienabcdgmbh'
company_3_nospace = 'uberwienabcdgesmbh'
由于我在字符串中查找不带空格的正则表达式,因此我可以看到所有三个公司的名称中都有合法的 ID。
我被困在哪里:
我可以说company_1、company_2 和company_3 中是否有合法ID,但我只能从company_1 中删除它。
事实上,我无法删除g m b h,因为它不匹配,但我可以说它是一个合法的id。我可以删除它的唯一方法是同时删除公司名称其余部分中的空格,我不想这样做(这只是最后的选择)
即使我要在gmbh 中插入空格以使其与g m b h 匹配,我也不会选择ges mbh 或ges m b h。
(请注意,其他国家也会发生同样的事情)
我的代码:
import re
re_code = re.compile('^gmbh|gmbh$|^gesmbh|gesmbh$')
comp_id_re = re_code.search(re.sub('\s+', '', company_name))
if comp_id_re:
company_id = comp_id_re.group()
company_name = re.sub(re_code, '', company_name).strip()
else:
company_id = ''
python 有没有办法理解从原始字符串中删除哪些字符?
或者如果我以某种方式(这是另一个问题)找到合法身份证间距的所有可能替代方案,它会更容易吗?即从gmbh 创建g mbh、gm bh、gmb h、g m bh 等...并将其用于匹配/提取?
我希望我的解释已经足够清楚了。想这个标题是相当困难的。
更新 1: 公司 ID 通常位于公司名称字符串的末尾。在某些国家/地区,它们有时会出现在开头。
更新 2: 我认为这会处理公司名称中的公司 ID。它适用于公司名称末尾的法律 ID,但不适用于开头的公司 ID
legal_regex = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$'
def foo(name, legal_regex):
#compile regex that matches company ids at beginning/end of string
re_code = re.compile(legal_regex)
#remove spaces
name_stream = name.replace(' ','')
#find regex matches for legal ids
comp_id_re = re_code.search(name_stream)
#save company_id, remove it from string
if comp_id_re:
company_id = comp_id_re.group()
name_stream = re.sub(re_code, '', name_stream).strip()
else:
company_id = ''
#restore spaced string (only works if id is at the end)
name_stream_it = iter(name_stream)
company_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name)
return (company_name, company_id)
【问题讨论】: