微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

考虑到标点​​符号,如何反转字符串的单词?

如何解决考虑到标点​​符号,如何反转字符串的单词?

这是我目前所拥有的:

def reversestring(thestring):
    words = thestring.split(' ')
    rev = ' '.join(reversed(words))
    return rev

stringing = input('enter string: ')
print(reversestring(stringing))

我知道我遗漏了一些东西,因为我需要标点符号来遵循逻辑。

假设用户输入了 Do or do not,there is no try.。结果应该是 .try no is there,not do or Do,但我只得到 try. no is there not,do or Do。我使用了一个简单的实现,它反转字符串中的所有字符,然后做一些检查所有单词并再次反转字符的操作,但只反转那些具有 ASCII 字母值的字符。

解决方法

您的代码完全按照它应该做的,在空格上拆分不会从单词中分隔一个点号逗号。


我建议您使用 re.findall 来获取您感兴趣的所有单词和标点

import re
def reversestring(thestring):
    words = re.findall(r"\w+|[.,]",thestring)
    rev = ' '.join(reversed(words))
    return rev

reversestring("Do or do not,there is no try.")  # ". try no is there,not do or Do"
,

试试这个(代码注释中的解释):

s = "Do or do not,there is no try."

o = []
for w in s.split(" "):
  puncts = [".",","!"] # change according to needs
  for c in puncts:
    # if a punctuation mark is in the word,take the punctuation and add it to the rest of the word,in the beginning
    if c in w:
      w = c + w[:-1] # w[:-1] gets everthing before the last char
  
  o.append(w)
  

o = reversed(o) # reversing list to reverse sentence
print(" ".join(o)) # printing it as sentence


#output: .try no is there,not do or Do
,

您可以使用正则表达式将句子解析为单词列表和分隔符列表,然后将单词列表反向并将它们组合在一起形成所需的字符串。您的问题的解决方案如下所示:

import re

def reverse_it(s):
    t = "" # result,empty string
    words = re.findall(r'(\w+)',s) # just the words
    not_s = re.findall(r'(\W+)',s) # everything else
    j = len(words)
    k = len(not_s)
    words.reverse() # reverse the order of word list
    if re.match(r'(\w+)',s): # begins with a word
        for i in range(k):
            t += words[i] + not_s[i]
        if j > k: # and ends with a word
            t += words[k]
    else: # begins with punctuation
        for i in range(j):
            t += not_s[i] + words[i]
        if k > j: # ends with punctuation
            t += not_s[j]
    return t #result

def check_reverse(p):
    q = reverse_it(p)
    print("\"%s\",\"%s\"" % (p,q) )

check_reverse('Do or do not,there is no try.')

输出

"Do or do not,there is no try.","try no is there,not do or Do."

这不是一个非常优雅的解决方案,但确实有效!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。