简体   繁体   English

如何使用 re.findall 查找字符串中的所有字符,包括特殊字符?

[英]How to use re.findall to find all characters in a string, including special characters?

If I have a list like this:如果我有这样的列表:

names = ['S. Planet', 'A. Planet-World', 'Dog World', 'Dog-Cat Planet']

I want to generate a new list with the last words from the list, including all special characters, like this:我想用列表中的最后一个单词生成一个新列表,包括所有特殊字符,如下所示:

new_names = [['S.', 'Planet'], ['A.', 'Planet-World'], ['Dog', 'World'], ['Dog-Cat', 'Planet']]

My code looks like this, but I can't figure out how to look at the special characters.我的代码看起来像这样,但我不知道如何查看特殊字符。 How would I fix this small thing?我该如何解决这个小问题? I'm new to Python and still learning.我是 Python 的新手,还在学习。

new_names = [(re.findall(r"([a-zA-Z]+)", x)) for x in names]
print(new_names)
#[['S', 'Planet'], ['A', 'Planet', 'World'], ['Dog', 'World'], ['Dog', 'Cat', 'Planet']]

I would appreciate any help.我将不胜感激任何帮助。 Thank you谢谢

You simply use the str.split() method like this:您只需像这样使用str.split()方法:

new_names = [name.split() for name in names]

Output: Output:

[
    ['S.', 'Planet'],
    ['A.', 'Planet-World'],
    ['Dog', 'World'],
    ['Dog-Cat', 'Planet']
]

I would do this differently.我会以不同的方式做到这一点。 It seems to me that all you're doing is splitting by space, so it makes sense to just look at that and not try to figure out how to handle the special characters.在我看来,您所做的只是按空间分割,所以只看它而不是试图弄清楚如何处理特殊字符是有意义的。

names = ['S. Planet', 'A. Planet-World', 'Dog World', 'Dog-Cat Planet']
new_names = map(str.split, names)

Since I'm not sure how common it is to use map/functional programming, I'll explain what it does.由于我不确定使用映射/函数式编程有多普遍,我将解释它的作用。 Map has the same effect as iterating through a list and then applying a function (the str.split function, in this case) to each element. Map 与遍历列表然后对每个元素应用 function(str.split function,在这种情况下)具有相同的效果。 The result of this is then returned as a new object that can be cast to a list.然后将其结果作为可以转换为列表的新 object 返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM