Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python字符串列表-列表理解_Python_String_List - Fatal编程技术网

python字符串列表-列表理解

python字符串列表-列表理解,python,string,list,Python,String,List,输入是字符串,输出是列表,每个单元格包含相应的单词。 单词被定义为字母和/或数字的序列。 例如,Ilove是一个单词,45tgfd是一个单词,54fss.不是一个单词,因为它有 让我们假设逗号只出现在单词后面 例如-“唐纳德·约翰·特朗普,生于1946年6月14日,是第45位” 应该成为 ['Donald'、'John'、'Trump'、'born'、'June'、'14'、'1946'、'is'、'the'、'45th'] 我试过用 [x.rstrip(',')用于行中的x.split(),如

输入是字符串,输出是列表,每个单元格包含相应的单词。 单词被定义为字母和/或数字的序列。 例如,
Ilove
是一个单词,
45tgfd
是一个单词,
54fss.
不是一个单词,因为它有

让我们假设逗号只出现在单词后面

例如-
“唐纳德·约翰·特朗普,生于1946年6月14日,是第45位”
应该成为
['Donald'、'John'、'Trump'、'born'、'June'、'14'、'1946'、'is'、'the'、'45th']

我试过用
[x.rstrip(',')用于行中的x.split(),如果x.rstrip(',').isalpha()或x.rstrip(',').isdigit()]
当line是原始字符串时,它变得凌乱和错误-由于
isdigit
isalpha
而无法检测到'45'


有什么想法吗?

你要找的是
str.isalnum

>>> import re

>>> s = 'Donald John Trump, born June 14, 1946, is the 45th'
>>> [i.strip(',') for i in re.split(r'\s+',s) if not re.search(r'^[\.]|\w+\.\w+|[\.]$',i)]
['Donald', 'Trump', 'born', 'June', '14', '1946', 'is', 'the', '45th']

>>> s2 = 'tes.t .test test. another word'
>>> [i.strip(',') for i in re.split(r'\s+',s2) if not re.search(r'^[\.]|\w+\.\w+|[\.]$',i)]
['another', 'word']
>>> [x for x in (s.rstrip(',') for s in line.split()) if x.isalnum()]
['Donald', 'John', 'Trump', 'born', 'June', '14', '1946', 'is', 'the', '45th']
>>>

同样要注意的是,我并不是通过在理解中使用生成器表达式来冗余调用
rstrip
,这也让我只通过
line.split()

您要查找的
str.isalnum

>>> [x for x in (s.rstrip(',') for s in line.split()) if x.isalnum()]
['Donald', 'John', 'Trump', 'born', 'June', '14', '1946', 'is', 'the', '45th']
>>>

还要注意的是,我并不是通过在理解中使用生成器表达式来冗余调用
rstrip
,这也让我只对
line.split()

执行一次新的传递+1@bernie是的,Python字符串方法有很多隐藏的宝石。对我来说是新的+1@bernie是 啊Python字符串方法有很多隐藏的宝石。使用
re
可能是最好的方法。“if not i.endswith('.')”在这里是不够的。大概OP不想在中间有一段时间,而EnthsAs不会选择这个词。另外,听起来他似乎想忽略除句号外以其他非字母数字字符结尾的单词。@sweetparon:我明白了。更新了对会计期间的回答。如果他想忽略其他非字母数字字符,他可以编辑问题。使用
re
可能是最好的方法。“If not i.endswith('.')”在这里是不够的。大概OP不想在中间有一段时间,而EnthsAs不会选择这个词。另外,听起来他似乎想忽略除句号外以其他非字母数字字符结尾的单词。@sweetparon:我明白了。更新了对会计期间的回答。如果他想忽略其他非字母数字字符,他可以编辑问题。对于处理“54fss”,预期的结果是你忽略整个事情,还是忽略结尾的句号?换言之,是否只有逗号得到了特别处理?对于处理“54fss”,预期的结果是您忽略了整个事件,还是忽略了结尾的句号?换言之,是否只有逗号得到特殊处理?