如何删除一些非英文字母的字符串?
How to delete some strings with non-English letters?
我是正则表达式和 Python 的新手。比如我的字符串列表是:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']
现在,我想删除所有非英文字母的字符串。所以,我只想保留:
['Aas','ASD','A']
我不知道如何使用 ^ 或其他东西来做这个?
而且,如果我的数据是:
my_try=pd.DataFrame({'try':
['Aas','1Aasdf','cc)','A2SD','.ASD',
'aaaa1','A','123%']})
然后我使用:
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
为什么会出现这样的错误:
Traceback (most recent call last):
File "C:\feng\myCode\infoExtract\venv\lib\site-packages\IPython \core\interactiveshell.py", line 3319, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-58-4bd95f31bd0c>", line 1, in <module>
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
File "<ipython-input-58-4bd95f31bd0c>", line 1, in <listcomp>
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
TypeError: string indices must be integers
我该如何解决这个问题,为什么会这样?
您有一个列表并希望将其过滤为仅包含与某些条件匹配的元素,具有 if
的列表推导非常适合:
my_list = [1, 2, 3, 4, 5, 6]
# just even numbers:
print([x for x in my_list if x % 2 == 0])
并且您想过滤仅由字母 'a' 到 'z' 和 'A' 到 'Z' 组成的任何内容,这是易于使用正则表达式的地方:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']
print([x for x in my_try if re.match('^[a-zA-Z]+$', x)])
正则表达式以 ^
开始并以 $
结束,告诉 re.match()
它应该匹配整个字符串,从头到尾。 [a-zA-Z]
定义一个字符 class,其中包含您要查找的字母。通常您会使用 \w
但这也包括数字。最后,+
意味着字符串中需要有 1 个或多个字符(如果使用 *
则为 0 个或多个字符)
我是正则表达式和 Python 的新手。比如我的字符串列表是:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']
现在,我想删除所有非英文字母的字符串。所以,我只想保留:
['Aas','ASD','A']
我不知道如何使用 ^ 或其他东西来做这个?
而且,如果我的数据是:
my_try=pd.DataFrame({'try':
['Aas','1Aasdf','cc)','A2SD','.ASD',
'aaaa1','A','123%']})
然后我使用:
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
为什么会出现这样的错误:
Traceback (most recent call last):
File "C:\feng\myCode\infoExtract\venv\lib\site-packages\IPython \core\interactiveshell.py", line 3319, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-58-4bd95f31bd0c>", line 1, in <module>
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
File "<ipython-input-58-4bd95f31bd0c>", line 1, in <listcomp>
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
TypeError: string indices must be integers
我该如何解决这个问题,为什么会这样?
您有一个列表并希望将其过滤为仅包含与某些条件匹配的元素,具有 if
的列表推导非常适合:
my_list = [1, 2, 3, 4, 5, 6]
# just even numbers:
print([x for x in my_list if x % 2 == 0])
并且您想过滤仅由字母 'a' 到 'z' 和 'A' 到 'Z' 组成的任何内容,这是易于使用正则表达式的地方:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']
print([x for x in my_try if re.match('^[a-zA-Z]+$', x)])
正则表达式以 ^
开始并以 $
结束,告诉 re.match()
它应该匹配整个字符串,从头到尾。 [a-zA-Z]
定义一个字符 class,其中包含您要查找的字母。通常您会使用 \w
但这也包括数字。最后,+
意味着字符串中需要有 1 个或多个字符(如果使用 *
则为 0 个或多个字符)