簡體   English   中英

python-從數組中的單詞中刪除字符串

[英]python - remove string from words in an array

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

#!/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. 我把所有單詞組合在一起; 這使得搜索它成為O(1)運算

那我們可以做

# 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]

第二種方法還使我們可以將生成器用於內部循環,從而減少了內存需求。

split()返回通過分割獲得的線段列表。 此外,

word = word.split('in')

不會修改您的列表,它只會修改要迭代的變量。

嘗試以此替換第二個循環:

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

從您的問題很難說出您想要在newlist想要什么,如果您只想要以“ in”開頭但刪除了“ in”的單詞,則可以使用slice

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

如果您希望以“ in”開頭的wordlist在刪除了“ in”之后仍在wordlist中(這是您的注釋中“ real”的意思嗎?),那么您需要一些不同的東西:

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

請注意,在Python中,我們使用list而不是“ array”。

假設wordlistwordlist列表。 以下代碼可以解決問題:

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

如果列表中的單詞數量很大,最好使用while循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM