[英]How do I extract an item in a list if it has a certain string in python?
我有一個列表,每個條目中有許多項目,由[]
分隔。 例如,
['1', 'pbkdf2_sha256$100000$sk3ONL23432fsdgUsHM62xa9XJHL+LkJHhK3cFGj8LYWGtOd8HC7Hs=',
'2018-09-25 19:32:41', '0', '', '', 'bob@trellis.law', 'Bob', 'Simon',
'bob@trellis.law', '1', '0', '2016-12-30 17:43:41', 'Bob Simon', 'Bob', '0', '1',
'', '[]', '', '0', '1', '0', '1', '', '', '1', '14', '191', '1', '0', '1', '0', '',
'', '', '0']
我想找到包含此正則表達式的條目,然后在變量中捕獲整行:
r = re.compile(r'\w+\+\d+@trellis\.law')
我沒有成功地嘗試過:
def import_csv(csv_file):
name_entries = []
with open(csv_file) as csvfile:
reader = csv.reader(csvfile)
name_entries.append(list(reader))
return name_entries
def exclude_regex_users(name_entries):
pulled_names = []
r = re.compile(r'\w+\+\d+@trellis\.law')
reader = csv.reader(name_entries)
for read in reader:
n = r.match(read)
if n:
pulled_names.append(n.group())
print(pulled_names)
我得到一個_csv.Error: iterator should return strings, not list (did you open the file in text mode?)
。
啊。
首先, import_csv
不應該將列表包裝在另一個列表中,它應該只返回行列表。
def import_csv(csv_file):
name_entries = []
with open(csv_file) as csvfile:
reader = csv.reader(csvfile)
return list(reader)
其次, exclude_entries
不需要使用csv
,在導入數據時已經使用, name_entries
是行列表。
第三,您應該只匹配包含 email 地址的列表元素。
您可以使用filter()
過濾列表,而不是循環。
def exclude_regex_users(name_entries):
r = re.compile(r'\w+\+\d+@trellis\.law')
pulled_names = filter(lambda row: r.match(row[6]) or r.match(row[9]), name_entries)
print(pulled_names)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.