【问题标题】:How to introduce typo in a string?如何在字符串中引入错字?
【发布时间】:2018-04-19 10:52:23
【问题描述】:

我想在字符串中引入拼写错误。我有一个参数typo_prob,它会以typo_prob 的概率翻转字符串中的一个字符。

例如,如果typo_prob 为0.1,则每十个字符将被一个随机字符替换。

到目前为止,我正在这样做:

message = "Where do you live?"
message = list(message)
n_chars_to_flip = round(len(message) * typo_prob)
pos_to_flip = []
for i in range(n_chars_to_flip):
    pos_to_flip.append(random.randint(0, len(message) - 1))
for pos in pos_to_flip:
    message[pos] = random.choice(string.ascii_lowercase)
message = ''.join(message)

请让我知道是否有更优雅或更有效的方法来做到这一点。

【问题讨论】:

  • 为什么不采取明显的方式呢?
  • 显而易见的方式是什么意思?

标签: python string


【解决方案1】:

我想这样做如下:

[x if random.random() >= 0.5 else random.choice(string.ascii_lowercase) for x in list(message)]

0.5 是字符被替换的概率。

【讨论】:

  • 因为应该是str,所以可能是''.join(x if ...)
  • random() 返回值 [0,1) 所以最好使用random() >= prob 在概率为 0 时捕获极端情况。
【解决方案2】:
import random
import string

message = "Where do you live?"
message = list(message)

for pos, char in enumerate(message):
    message[pos] = random.choice(string.ascii_lowercase) if random.random() < 0.1 else char

message = "".join(message)

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2012-09-02
    相关资源
    最近更新 更多