python - 从数组中的单词中删除字符串

时间:2011-01-15 03:27:58

标签: python arrays list string

#!/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”?现在它不起作用

4 个答案:

答案 0 :(得分:2)

#!/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
  1. 使用'with'可确保文件始终正确关闭;
  2. 我将allWords设为一套;这使得搜索它成为O(1)操作
  3. 然后我们可以做

    # 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 :(得分:1)

split()返回通过拆分获得的细分列表。此外,

word = word.split('in')

不会修改您的列表,它只是修改正在迭代的变量。

尝试用这个替换你的第二个循环:

for i in range(len(newlist)):
    word = newlist[i].split('in', 1)
    newlist[i] = word[1]

答案 2 :(得分:1)

如果您只想要以“in”开头但删除了“in”的单词,那么很难从newlist中找出您想要的内容,那么您可以使用slice

newlist = [word[2:] for word in wordlist if word.startswith('in')]

如果你想要以“in”开头的单词一旦被“删除”仍然在wordlist中(在你的评论中你的意思是“真实”吗?)那么你需要一些东西差别很小:

newlist = [word for word in wordlist if word.startswith('in') and word[2:] in wordlist

请注意,在Python中我们使用的是list,而不是“数组”。

答案 3 :(得分:0)

假设wordlist是单词列表。以下代码应该可以解决问题:

for i in range(len(wordlist)):
    if wordlist[i].startswith("in"):
        wordlist[i] = wordlist[i][2:]

如果列表中的单词数量非常大,最好使用while循环。

相关问题