简体   繁体   English

如何在字符串中引入错字?

[英]How to introduce typo in a string?

I would like to introduce typos in a string. 我想在字符串中引入错别字。 I have a parameter typo_prob which would flip a character in a string with a probability of typo_prob. 我有一个参数typo_prob,它将以字符串typo_prob的概率翻转字符串中的字符。

For example, if typo_prob is 0.1, every tenth character will be replaced by a random character. 例如,如果typo_prob为0.1,则将用随机字符替换每十分之一字符。

So far I am doing this: 到目前为止,我正在这样做:

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)

Please let me know if there is a more elegant or efficient way to do this. 请让我知道是否有更优雅或更有效的方法。

I'd to this as following: 我对此如下:

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

0.5 is the probabilty the character is replaced. 0.5是替换字符的概率。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM