gpt4 book ai didi

python - 我如何从字符串中删除标点符号,然后再将其添加回同一索引?

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:26 25 4
gpt4 key购买 nike

我想让程序假设我的 word_str 是“例如,这是‘剑桥大学’。”如果单词的长度大于 3 个字符,它将保留单词的第一个和最后一个字母并在单词内部加扰。我的问题是它在单词的开头或结尾错误地打乱了带有标点符号的单词。我需要它来洗牌,以便标点符号保留在正确的索引中,然后保留单词的第一个和最后一个字母,并洗牌单词的内部,如果有的话,在末尾添加标点符号。有什么想法吗?

def scramble_word(word_str):
char = ".,!?';:"
import random
if len(word_str) <= 3:
return word_str + ' '
else:
word_str = word_str.strip(char)
word_str = list(word_str)
scramble = word_str[1:-1]
random.shuffle(scramble)
scramble = ''.join(scramble)
word_str = ''.join(word_str)
new_word = word_str[0] + scramble + word_str[-1]
return new_word + ' '

最佳答案

使用正则表达式:

import random
import re

random.seed(1234) #remove this in production, just for replication of my results

def shuffle_word(m):
word = m.group()
inner = ''.join(random.sample(word[1:-1], len(word) - 2))
return '%s%s%s' % (word[0], inner, word[-1])

s = """This is 'Cambridge University' for example."""

print re.sub(r'\b\w{3}\w+\b', shuffle_word, s)

哪个打印

Tihs is 'Cadibrgme Uinrtvsiey' for exlampe.

re.sub 允许您向它传递一个函数(接受正则表达式匹配对象)而不是替换字符串。

编辑 - 没有正则表达式

from StringIO import StringIO

def shuffle_word(m):
inner = ''.join(random.sample(m[1:-1], len(m) - 2))
return '%s%s%s' % (m[0], inner, m[-1])

def scramble(text)
sio = StringIO(text)
accum = []
start = None
while sio.tell() < sio.len:
char = sio.read(1)
if start is None:
if char.isalnum():
start = sio.tell() - 1
else:
accum.append(char)
elif not char.isalnum():
end = sio.tell() - 1
sio.seek(start)
accum.append(shuffle_word(sio.read(end - start)))
print accum[-1]
start = None
else:
if start is not None:
sio.seek(start)
word = sio.read()
if len(word) > 3:
accum.append(shuffle_word(sio.read()))
else:
accum.append(word)

return ''.join(accum)

s = """This is 'Cambridge University' for example."""
print scramble(s)

关于python - 我如何从字符串中删除标点符号,然后再将其添加回同一索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com