python - 从数组中的单词去除字符串
#!/usr/bin/python #this looks for words in dictionary that begin with 'in' and the suffix is a real word wordlist = [line.strip() for line in open('/usr/share/dict/words')] newlist = [] for word in wordlist: if word.startswith("in"): newlist.append(word) for word in newlist: word = word.split('in') print newlist
我该怎么做才能让程序把所有以“in”开头的单词中的“in”去掉呢?现在这个功能不太好使。
4 个回答
1
从你的问题中很难看出你想要在 newlist
里得到什么。如果你只是想要那些以 "in" 开头的单词,但去掉 "in" 的话,你可以使用一个叫做 切片 的方法:
newlist = [word[2:] for word in wordlist if word.startswith('in')]
如果你想要那些以 "in" 开头的单词在去掉 "in" 后仍然保留在 wordlist
中(你在评论里提到的 "真实" 是这个意思吗?),那么你需要用稍微不同的方法:
newlist = [word for word in wordlist if word.startswith('in') and word[2:] in wordlist
要注意,在Python里我们用的是 list
,而不是 "数组"。
2
- 使用'with'可以确保文件始终被正确关闭;
- 我把allWords变成了一个集合,这样搜索它的速度就变成了O(1),也就是非常快。
#!/usr/bin/env python
# Look for all words beginning with 'in'
# such that the rest of the word is also
# a valid word.
# load the dictionary:
with open('/usr/share/dict/word') as inf:
allWords = set(word.strip() for word in inf) # one word per line
然后我们可以这样做
# get the remainder of all words beginning with 'in'
inWords = [word[2:] for word in allWords if word.startswith("in")]
# filter to get just those which are valid words
inWords = [word for word in inWords if word in allWords]
或者把它写成一个单一的语句,比如
inWords = [word for word in (word[2:] for word in allWords if word.startswith("in")) if word in allWords]
用第二种方法还可以在内部循环中使用生成器,这样可以减少内存的使用。
1
split()
是一个函数,它会把一个字符串分割成多个部分,并把这些部分放到一个列表里。简单来说,就是把一段话切成几块。
word = word.split('in')
这个函数不会改变你原来的列表,它只是改变了正在循环处理的那个变量。
你可以试着把你的第二个循环换成下面这个:
for i in range(len(newlist)):
word = newlist[i].split('in', 1)
newlist[i] = word[1]