语句后
list = []
你不能使用内置list
class和明白,你可以花大约一个小时左右,这就是为什么我们要避免的内置插件的名称,我们的对象。
更多在this answer。
函数检查与一个 '' 结尾的单词。“”
声明如果
"." in word
检查word
包含点符号(如"." in "sample.text"
将好的工作,而它根本不点结尾),如果你需要检查它与点结束 - 使用str.endswith
方法。
我想,以确保重复的话不要在列表中去。
只是确保在存储尚未存储的文件之前。
最后,我们可以写
def endwords(sent, end='.'):
unique_words = []
words = sent.split()
for word in words:
if word.endswith(end) and word not in unique_words:
unique_words.append(word)
return unique_words
测试
>>>sent = ' '.join(['some.', 'oth.er'] * 10)
>>>unique_words = endwords(sent)
>>>unique_words
['some.']
PS
如果顺序并不重要 - 使用set
,很会照顾重复的(仅适用可拆分类型,str
可哈希):
def endwords(sent, end='.'):
unique_words = set()
words = sent.split()
for word in words:
if word.endswith(end) and word not in unique_words:
unique_words.add(word)
return unique_words
或一套理解
def endwords(sent, end='.'):
words = sent.split()
return {word for word in words if word.endswith(end)}
你应该避免使用内置插件的名称为您的对象(如'list','dict','str'等) –