我有一个如下所示的字符串,需要删除相似的连续单词。
mystring = "my friend's new new new new and old old cats are running running in the street"
我的输出应如下所示。
myoutput = "my friend's new and old cats are running in the street"
我正在使用以下python代码来做到这一点。
mylist = []
for i, w in enumerate(mystring.split()):
for n, l in enumerate(mystring.split()):
if l != w and i == n-1:
mylist.append(w)
mylist.append(mystring.split()[-1])
myoutput = " ".join(mylist)
但是,我的代码是O(n)^2
,并且由于我拥有庞大的数据集而效率很低。我想知道在python中是否有更有效的方法。
很高兴在需要时提供更多详细信息。
答案 0 :(得分:3)
import itertools
>> ' '.join(k for k, _ in itertools.groupby(mystring.split()))
"my friend's new and old cats are running in the street"
mystring.split()
拆分mystring
。itertools.groupby
通过k
有效地对连续单词进行分组。输入字符串的大小复杂度是线性的。
答案 1 :(得分:2)
短正则表达式魔术:
import re
mystring = "my friend's new new new new and old old cats are running running in the street"
res = re.sub(r'\b(\w+\s*)\1{1,}', '\\1', mystring)
print(res)
正则表达式模式详细信息:
\b
-单词边界(\w+\s*)
-一个或多个单词字符\w+
,后跟任意数量的空格字符\s*
-包含在捕获的组(...)
\1{1,}
-指第一个捕获的组发生了一次或多次{1,}
输出:
my friend's new and old cats are running in the street
答案 2 :(得分:2)
尝试:
mystring = "my friend's new new new new and old old cats are running running in the street"
words = mystring.split()
answer = [each_pair[0] for each_pair in zip(words, words[1:]) if each_pair[0] != each_pair[1]] + [words[-1]]
print(' '.join(answer))
输出:
my friend's new and old cats are running in the street
在这种情况下,我们对连续单词的元组进行迭代,并在每个元组中附加第一个单词以回答该元组中的两个单词是否不同。最后,我们还将最后一个单词附加到答案上
答案 3 :(得分:2)
现在换一些不同的东西。在原始字符串非常大的情况下,此解决方案将使用生成器,直到最终重新组装结果字符串以尽可能提高内存效率为止。
import re
def remove_duplicates_helper(s):
words = (x.group(0) for x in re.finditer(r"[^\s]+", s))
current = None
for word in words:
if word != current:
yield word
current = word
def remove_duplicates(s):
return ' '.join(remove_duplicates_helper(s))
mystring = "my friend's new new new new and old old cats are running running in the street"
print(remove_duplicates(mystring))
我朋友的新老猫在街上奔跑
答案 4 :(得分:1)
请在下面找到我的代码:
def strip2single(textarr):
if len(textarr)==0:
return ""
result=textarr[0]
for i in range(1,len(textarr)):
if textarr[i]!=textarr[i-1]:
result=result+' '+textarr[i]
return(result)
mystring = "my friend's new new new new and old old cats are running running in the street"
y=strip2single(mystring.split())
print(y)
答案 5 :(得分:1)
存在该问题的O(n)解决方案。
mystring = "my friend's new new new new and old old cats are running running in the street"
分解为文字
words = mystring.split()
如果当前单词等于前一个单词,则跳过
myoutput = ' '.join([x for i,x in enumerate(words) if i==0 or x!=words[i-1]])
答案 6 :(得分:1)
枚举操作执行两次。更改与此类似的代码可以使您的代码高效。
mylist = []
l1 = enumerate(mystring.split())
for i, w in l1:
for n, l in l1:
if l != w and i == n-1:
mylist.append(w)
mylist.append(mystring.split()[-1])
myoutput = " ".join(mylist)