[英]Python Regex re.compile query
我正在嘗試使用正則表達式查詢從名稱列表中找到所需名稱的列表。
csv 文件:僅供參考,我將國家/地區從大寫字母轉換為小寫字母
搜索列表:
['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']
搜索列表的searchList
: [(region)(Category)]_[EmployeeName].[country]
(region)(Category)
連接在一起。
我正在嘗試獲取每個組的列表,
[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]
使用以下正則表達式查詢: \<({region}).*\{country}\>
for region, country in regionCountry:
query = f"\<({region}).*\{country}\>"
r = re.compile(query)
group = list(filter(r.match, searchList))
我也嘗試過re.search
,但該group
始終為None
誰能告訴我腳本哪里出了問題。? 謝謝
沒有正則表達式:
split
數據
entries = ['AU.LS1_james.aus', 'AU.LS1_scott.aus', 'AP.LS1_amanda.usa', 'AP.LS1_john.usa', 'LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
解決方案 1 :簡單的dict
和setdefault
d = {}
for entry in entries:
d.setdefault(entry.split('.',1)[0], []).append(entry)
解決方案2 : defaultdict
from collections import defaultdict
d = defaultdict(list)
for entry in entries:
d[entry.split('.',1)[0]].append(entry)
結果在d.values()
>>> list(d.values())
[['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']]
我感謝大家試圖協助我的問題。 這個答案很適合我的使用。 出於某種原因 python 不喜歡\<
和\>
。 所以我只是刪除了它們並且效果很好。 沒想到使用re
庫會有一些限制。
答案: f({region}).*\{country}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.