![](/img/trans.png)
[英]how to find words in a sentence that have even reverse of those words in python
[英]reverse words in a sentence using Python?
我試圖在一個句子中反轉一個單詞。
例如:
arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
應該
[ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't' ]
我寫了下面的代碼,它反轉整個數組然后反轉每個單詞
def reverse_words(arr):
def mirrorReverse(arr,start,end):
while(start<end):
tmp=arr[start]
arr[start]=arr[end]
arr[end]=tmp
start+=1
end-=1
n=len(arr)
mirrorReverse(arr,0,n-1)
for i in range(len(arr)):
if arr[i]==' ' and start==0: #first word
mirrorReverse(arr,start,i-1)
start=i+1
elif i==len(arr)-1: #last word
mirrorReverse(arr,start,i)
elif arr[i]==' ' and start!=None: #middle
mirrorReverse(arr,start,i-1)
start=i+1
return arr
這工作正常並輸出所需的答案但是當我使用不同的示例時它不起作用:
測試 1:
["a"," "," ","b"]
預期:
["b"," "," ","a"]
實際:
['a', ' ', ' ', 'b']
test2:
["y","o","u"," ","w","i","t","h"," ","b","e"," ","f","o","r","c","e"," ","t","h","e"," ","m","a","y"]
output:
['y', 'o', 'u', ' ', 'w', 'i', 't', 'h', ' ', 'b', 'e', ' ', 'f', 'o', 'r', 'c', 'e', ' ', 't', 'h', 'e', ' ', 'm', 'a', 'y']
即使 test2 類似於上面的主要示例,它工作得非常好。 任何幫助
首先,在 Python 提示符下:
>>> def revwords(str):
... list = str.split()
... list.reverse()
... return ' '.join(list)
...
>>> revwords('The quick brown fox jumped over the lazy dogs.')
'dogs. lazy the over jumped fox brown quick The'
通過進行一些重組和拆分,我們可以將上述內容與所需的字符數組表示一起使用。 在 Python 提示符處繼續:
>>> list(revwords(''.join(['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'])))
['w', 'o', 'r', 'l', 'd', ' ', 'H', 'e', 'l', 'l', 'o']
請針對您的具體案例嘗試以下解決方案:
if __name__ == "__main__":
x = ['p', 'e', 'r', 'f', 'e', 'c', 't', '', 'm', 'a', 'k', 'e', 's', '', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e']
words = []
word = ""
for letter in x:
if len(letter) == 1:
word += letter
else:
words.append(word)
word = ""
words.append(word) # add the last one
result = []
for w in words[::-1]:
for letter in w:
result.append(letter)
result.append("")
result.pop() # remove the last one ""
print(result)
這是反轉句子然后加入的一種方法:
sentence = "perfect makes practice"
s_list = sentence.split(" ")
s_list.reverse()
print(" ".join(s_list))
你的代碼看起來不錯。 您的示例和代碼中有兩個空格。但是測試用例有一個空格。 當我復制粘貼您的代碼並將 if's 中的雙空格更改為單個空格時,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.