[英]re.findall within a list in python
I have a list as below.我有一个清单如下。
sample_text = ['199.72.81.55 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245',
'unicomp6.unicomp.net -- [01/Jul/1995:00:00:06 -0400] "Get /shuttle/countdown/HTTP/1.0" 200 3985',
'199.120.110.21 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245',
'burger.letters.com -- [01/Jul/1995:00:00:06 -0400] "Get /shuttle/countdown/HTTP/1.0" 200 3985',
'205.172.11.25 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245']
I need to get all host names in a list.我需要在列表中获取所有主机名。 Expected result is as below.
预期结果如下。
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
My code is:我的代码是:
for i in range(0, len(sample_text)):
s=sample_text[i]
host.append(re.findall('[\d]*[.][\d]*[.][\d]*[.][\d]*|[a-z0-9]*[.][a-z]*[.][a-z]*', s))
print(host)
My output:我的 output:
[['199.72.81.55'], ['unicomp6.unicomp.net'], ['199.120.110.21'], ['burger.letters.com'], ['205.172.11.25']]
How do I fix this?我该如何解决?
Without using regex you can just str.split
on '--'
and take the first part在不使用正则表达式的情况下,您可以在
'--'
上进行str.split
并获取第一部分
>>> [i.split('--')[0].strip() for i in sample_text]
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
Similar idea, but using regex类似的想法,但使用正则表达式
>>> import re
>>> [re.match(r'(.*) -- .*', i).group(1) for i in sample_text]
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
In both cases you can use a list comprehension to replace your for
loop在这两种情况下,您都可以使用列表理解来替换您的
for
循环
You can easily flatten host
:您可以轻松展平
host
:
host = []
for i in range(0, len(sample_text)):
s=sample_text[i]
host += re.findall('[\d]*[.][\d]*[.][\d]*[.][\d]*|[a-z0-9]*[.][a-z]*[.][a-z]*', s)
print(host)
Output: Output:
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
re.findall()
returns a list of strings. re.findall()
返回一个字符串列表。
Documentation: https://docs.python.org/3/library/re.html#re.findall文档: https://docs.python.org/3/library/re.html#re.findall
.append
will add the list as a single item to the new list. .append
会将列表作为单个项目添加到新列表中。
Try:尝试:
host.extend(
Documentation: https://docs.python.org/3/tutorial/datastructures.html文档: https://docs.python.org/3/tutorial/datastructures.html
I just used.extend instead of append which resolved the issue.我只是使用 .extend 而不是 append 解决了这个问题。
host.extend(re.findall('[\d]*[.][\d]*[.][\d]*[.][\d]*|[a-z0-9]*[.][a-z]*
[.][a-z]*', s))
Maybe try something like this:也许尝试这样的事情:
sum(host, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.