从随机字符串中提取单词



下面我有一些字符串在列表中:

some_list = ['a','l','p','p','l','l','i','i','r',i','r','a','a']

现在我想从这个列表中取出单词april。这个列表中只有两个april。所以我想从这个列表中取出两个april并将它们附加到另一个extract列表中。

那么提取列表应该是这样的:

extract = ['aprilapril']

extract = ['a','p','r','i','l','a','p','r','i','l']

我试了很多次,试图把extract中的一切都整理好,但我似乎仍然不能得到它。

但我知道我可以这样做

a_count = some_list.count('a')
p_count = some_list.count('p')
r_count = some_list.count('r')
i_count = some_list.count('i')
l_count = some_list.count('l')
total_count = [a_count,p_count,r_count,i_count,l_count]
smallest_count = min(total_count)
extract = ['april' * smallest_count]

如果我只使用上面的代码,我就不会在这里了

因为我制定了一些规则来解决这个问题


每个字符(a,p,r,i和l)都是一些神奇的代码元素,这些代码元素不能凭空创建;它们是一些唯一的代码元素,有一些唯一的标识符,就像一个与它们相关联的秘密号码。因此,您不知道如何创建这些神奇的代码元素,获得代码元素的唯一方法是将它们提取到列表中。

每个字符(a,p,r,i和l)必须是有序的。把它们想象成某种链条,它们只有在一起才能起作用。这意味着我们必须把p放在a的前面,l必须放在最后。

这些重要的代码元素是某种绝密的东西,所以如果你想要得到它,唯一的方法就是将它们提取到一个列表中。


下面是一些不正确的的例子方法:(打破规则)

import re
word = 'april'
some_list = ['aaaaaaappppppprrrrrriiiiiilll']
regex = "".join(f"({c}+)" for c in word)
match = re.match(regex, text)
if match:
lowest_amount = min(len(g) for g in match.groups())
print(word * lowest_amount)
else:
print("no match")
from collections import Counter
def count_recurrence(kernel, string):
# we need to count both strings
kernel_counter = Counter(kernel)
string_counter = Counter(string)
effective_counter = {
k: int(string_counter.get(k, 0)/v)
for k, v in kernel_counter.items()
}
min_recurring_count = min(effective_counter.values())
return kernel * min_recurring_count

这可能听起来很愚蠢,但这实际上是一个难题(对我来说)。我最初设计这个问题是为了练习python,但它比我想象的要难得多。我只是想看看别人是怎么解决这个问题的。

如果有人知道如何解决这个荒谬的问题,请帮助我,我只是一个14岁的孩子试图做python。非常感谢。

我不知道你说的"不能复制也不能删除神奇的代码"是什么意思。-如果你想把它们放在你的输出列表中,你需要"copy"他们不知何故。

顺便说一句,你的示例代码(a_count = some_list.count('a')等)将无法工作,因为count将始终返回零。

也就是说,一个可能的解决方案是
worklist = [c for c in some_list[0]]
extract = []
fail = False
while not fail:
lastpos = -1
tempextract = []
for magic in magics:
if magic in worklist:
pos = worklist.index(magic, lastpos+1)
tempextract.append(worklist.pop(pos))
lastpos = pos-1
else:
fail = True
break
else:
extract.append(tempextract)

或者,如果您不想在找到元素时对它们进行pop,您可以计算第一个元素("a")的所有出现的位置,并在每次迭代开始时将lastpos设置为每个位置

可能不是最有效的方法,尽管代码可以工作并且更显式地理解程序逻辑:

some_list = ['aaaaaaappppppprrrrrriiiiiilll']
word = 'april'
extract = []
remove = []
string = some_list[0]
for x in range(len(some_list[0])//len(word)): #maximum number of times `word` can appear in `some_list[0]`
pointer = i = 0
while i<len(word):
j=0
while j<(len(string)-pointer):
if string[pointer:][j] == word[i]:
extract.append(word[i])
remove.append(pointer+j)
i+=1
pointer = j+1
break
j+=1
if i==len(word):
for r_i,r in enumerate(remove):
string = string[:r-r_i] + string[r-r_i+1:]
remove = []
elif j==(len(string)-pointer):
break
print(extract,string)

最新更新