用一个随机字符替换空格(来回转换)在Python中。

huangapple go评论69阅读模式
英文:

Replace space with a random character (there and back) in Python

问题

Here's the translated code for your problem:

## 问题

我有一个大海捞针”:

```python
source = '''    "El Niño" "Hi there! How was class?"
        "Me" "Good..."
        "I can't bring myself to admit that it all went in one ear and out the other."
        "But the part of the lesson about writing your own résumé was really interesting!"
        "Me" "Are you going home now? Wanna walk back with me?"
        "El Niño" "Sure!"'''

我有一个“口罩”:

out_table = '→☺☻♥♦♣♠•◘○§¶▬↨↑↓←∟↔'

我有一个“令牌” -- (单个空格)。

它们的所有元素都是字符串(<str>的类)。

我需要一个函数,该函数将:

  1. 遍历“大海捞针”(source
  2. 将令牌( )的每个出现替换为从“口罩”中随机选择单个字符
  3. 将替换过程后的新“大海捞针”打印出来

最后,我需要一个类似的方法,它将恢复上述过程,因此它将将列表→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔中的每个出现(每个字符)替换为 (空格)。

期望结果

一个示例(可以变化 -- 随机性)示例结果如下(只是一个打印输出):

↔◘↔▬"El→Niño""Hi∟there!↓How↨was↨class?"
↔◘↔▬"Me""Good..."
♥♦♣♠"I↓can't↨bring&#167;myself↓to∟admit↓that↓it↓all↓went↓in↓one&#167;ear↓and↓out&#167;the↓other."
↔◘↔▬"But☻the☻part☻of↓the→lesson∟about↓writing↓own↓résumé&#167;was&#167;really→interesting!"
↔◘↔▬"Me""Are↓you☻going↓home&#167;now?→Wanna↓walk∟back↓with↓me?"
♥♦♣♠"El↓Niño""Sure!"

假设:

  • 每个空格都必须在“大海捞针”中替换
  • 不是每个字符都必须使用“口罩”中的字符

因此,在“最随机的边界”情况下,所有空格都将替换为相同的字符。只要整个过程可以还原为原始的“大海捞针”(source),这并不是问题。

我的研究和解决方案尝试

由于这是我的第一段Python代码,我在Python和非Python相关的问题以及网上网上上浏览了许多与此相关的问题,我提出了以下想法:

import random 
def swap_charcter(message, character, mask):
    the_list = list(message)
    for i in random.sample(range(len(the_list)), len(list(mask))):
        the_list[i] = random.choice(mask)
    return message.join(the_list)
    
# print(swap_charcter('tested', 'e', '!#'))
print(swap_charcter('tested', 'e','→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔'))

但是...我一定做错了什么,因为每次我运行此代码片段(或许多其他代码片段),只需将空格作为参数运行,我都会收到“样本大于总体或为负数”的错误。

有人可以在这里帮助一下吗?谢谢。

编辑:根据评论建议,我已将list(character)替换为list(message)


I hope this helps! Let me know if you have any questions or need further assistance.

<details>
<summary>英文:</summary>

## The problem

I have a _haystack_:

    source = &#39;&#39;&#39;    &quot;El Ni&#241;o&quot; &quot;Hi there! How was class?&quot;

        &quot;Me&quot; &quot;Good...&quot;

        &quot;I can&#39;t bring myself to admit that it all went in one ear and out the other.&quot;
        
        &quot;But the part of the lesson about writing your own r&#233;sum&#233; was really interesting!&quot;

        &quot;Me&quot; &quot;Are you going home now? Wanna walk back with me?&quot;

        &quot;El Ni&#241;o&quot; &quot;Sure!&quot;&#39;&#39;&#39;

I have a _mask_:

    out_table = &#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;

And I have a _token_ -- ` ` (single space).

All their elements are _strings_ (`class of &lt;str&gt;`).

I need a function that will:

1. Iterate through _haystack_ (`source`)
2. Replace each occurrence of _token_ (` `) with a _single character_ **randomly picked** from the _mask_
3. Will print resulting _new haystack_ after the replacement process

Finally, I need a similar method that will revert the above process, so it will replace each occurrence (every character) of the `→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔` list into ` ` (space).

## Expected result

An example (can vary -- randomness) example result is (just a printout):

    ↔◘↔▬&quot;El→Ni&#241;o&quot;↓&quot;Hi∟there!↓How↨was↨class?&quot;

    ↔◘↔▬&quot;Me&quot;↓&quot;Good...&quot;

    ♥♦♣♠&quot;I↓can&#39;t↨bring&#167;myself↓to∟admit↓that↓it↓all↓went↓in↓one&#167;ear↓and↓out&#167;the↓other.&quot;

    ↔◘↔▬&quot;But☻the☻part☻of↓the→lesson∟about↓writing↓own↓r&#233;sum&#233;&#167;was&#167;really→interesting!&quot;

    ↔◘↔▬&quot;Me&quot;↓&quot;Are↓you☻going↓home&#167;now?→Wanna↓walk∟back↓with↓me?&quot;

    ♥♦♣♠&quot;El↓Ni&#241;o&quot;→&quot;Sure!&quot;

Assumptions:

- **Every** space must be replaced in the _haystack_
- **Not every** character out of _mask_ must be used

So, I the most &quot;randomly border&quot; scenario _all_ spaces will be replaced with _the same_ character. Which isn&#39;t a problem at all as long as the whole process is reversible back to the original _haystack_ (`source`).

## My research and solution attempt

Since this is my first Python code, I have browsed a number of [Python](https://stackoverflow.com/questions/34338788/python-replace-3-random-characters-in-a-string-with-no-duplicates) and [non-Python](https://stackoverflow.com/a/34800817/1469208) related [questions](https://stackoverflow.com/q/32119073/1469208) here and in [the net](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) and I have come with the following idea:

    import random 
    def swap_charcter(message, character, mask):
        the_list = list(message)
        for i in random.sample(range(len(the_list)), len(list(mask))):
            the_list[i] = random.choice(mask)
        return message.join(the_list)
        
    # print(swap_charcter(&#39;tested&#39;, &#39;e&#39;, &#39;!#&#39;))
    print(swap_charcter(&#39;tested&#39;, &#39;e&#39;,&#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;))

But... I must be doing something wrong, because each time I run this (or many, many other) piece of code with just a space as an argument, I am getting the _Sample larger than population or is negative_ error.

Can someone help here a little bit? Thank you.

**EDIT**: _I have replaced `list(character)` → `list(message)`, as suggested in the comments_.

</details>


# 答案1
**得分**: 2

使用 [`re.sub`](https://docs.python.org/3/library/re.html#re.sub)(正则表达式替换)将所有空格替换为来自你的 `out_table` 的 [`random.choice`](https://docs.python.org/3/library/random.html#random.choice)。

要还原,请使用 [`str.translate`](https://docs.python.org/3/library/stdtypes.html#str.translate) 和 [`str.maketrans`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) 将所有字符从 `out_table` 翻译为空格。

示例:
```py
import re
import random

source = '&#39;&#39;&#39;    &quot;El Ni&#241;o&quot; &quot;Hi there! How was class?&quot;

    &quot;Me&quot; &quot;Good...&quot;

    &quot;I can&#39;t bring myself to admit that it all went in one ear and out the other.&quot;
    
    &quot;But the part of the lesson about writing your own r&#233;sum&#233; was really interesting!&quot;

    &quot;Me&quot; &quot;Are you going home now? Wanna walk back with me?&quot;

    &quot;El Ni&#241;o&quot; &quot;Sure!&quot;&#39;&#39;&#39;

out_table = '&#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;

result = re.sub(' &#39;, lambda m: random.choice(out_table), source)
print(result)

original = result.translate(str.maketrans(out_table, '&#39; &#39; * len(out_table)))
print(original)

Output:

↨◘◘↑&quot;El▬Ni&#241;o&quot;○&quot;Hi∟there!→How♦was◘class?&quot;

☻↔•☺&quot;Me&quot;&#167;&quot;Good...&quot;

↓↨•∟&quot;I↓can&#39;t∟bring☺myself∟to♥admit▬that&#167;it▬all☻went↔in&#182;one○ear♦and•out☻the←other.&quot;
←♦•○
♣→♥↓&quot;But♣the☺part♦of◘the↑lesson○about↑writing▬your♠own○r&#233;sum&#233;↨was∟really♦interesting!&quot;

↨∟♠↑&quot;Me&quot;←&quot;Are→you&#182;going←home○now?→Wanna☺walk♣back&#182;with◘me?&quot;

◘←☺○&quot;El↨Ni&#241;o&quot;&#167;&quot;Sure!&quot;
    &quot;El Ni&#241;o&quot; &quot;Hi there! How was class?&quot;

    &quot;Me&quot; &quot;Good...&quot;

    &quot;I can&#39;t bring myself to admit that it all went in one ear and out the other.&quot;
    
    &quot;But the part of the lesson about writing your own r&#233;sum&#233; was really interesting!&quot;

    &quot;Me&quot; &quot;Are you going home now? Wanna walk back with me?&quot;

    &quot;El Ni&#241;o&quot; &quot;Sure!&quot;
英文:

Use a re.sub (regular expression substitution) to change all spaces to a random.choice from your out_table.

To restore, use str.translate and str.maketrans to translate all characters from out_table to spaces.

Example:

import re
import random

source = &#39;&#39;&#39;    &quot;El Ni&#241;o&quot; &quot;Hi there! How was class?&quot;

    &quot;Me&quot; &quot;Good...&quot;

    &quot;I can&#39;t bring myself to admit that it all went in one ear and out the other.&quot;
    
    &quot;But the part of the lesson about writing your own r&#233;sum&#233; was really interesting!&quot;

    &quot;Me&quot; &quot;Are you going home now? Wanna walk back with me?&quot;

    &quot;El Ni&#241;o&quot; &quot;Sure!&quot;&#39;&#39;&#39;

out_table = &#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;

result = re.sub(&#39; &#39;, lambda m: random.choice(out_table), source)
print(result)

original = result.translate(str.maketrans(out_table, &#39; &#39; * len(out_table)))
print(original)

Output:

↨◘◘↑&quot;El▬Ni&#241;o&quot;○&quot;Hi∟there!→How♦was◘class?&quot;

☻↔•☺&quot;Me&quot;&#167;&quot;Good...&quot;

↓↨•∟&quot;I↓can&#39;t∟bring☺myself∟to♥admit▬that&#167;it▬all☻went↔in&#182;one○ear♦and•out☻the←other.&quot;
←♦•○
♣→♥↓&quot;But♣the☺part♦of◘the↑lesson○about↑writing▬your♠own○r&#233;sum&#233;↨was∟really♦interesting!&quot;

↨∟♠↑&quot;Me&quot;←&quot;Are→you&#182;going←home○now?→Wanna☺walk♣back&#182;with◘me?&quot;

◘←☺○&quot;El↨Ni&#241;o&quot;&#167;&quot;Sure!&quot;
    &quot;El Ni&#241;o&quot; &quot;Hi there! How was class?&quot;

    &quot;Me&quot; &quot;Good...&quot;

    &quot;I can&#39;t bring myself to admit that it all went in one ear and out the other.&quot;
    
    &quot;But the part of the lesson about writing your own r&#233;sum&#233; was really interesting!&quot;

    &quot;Me&quot; &quot;Are you going home now? Wanna walk back with me?&quot;

    &quot;El Ni&#241;o&quot; &quot;Sure!&quot;

答案2

得分: 1

A quick example:

import random 

mask = '→☺☻♥♦♣♠•◘○§¶▬↨↑↓←∟↔'
original = 'The quick fox jumps over the lazy dog'

pieces = original.split(' ')
filled = [piece+random.choice(mask) for piece in pieces]
result = ''.join(filled)
result = result[0:-1]

print(result)

Result:
The♥quick○fox∟jumps•over↨the∟lazy♠dog

This method takes your string and:

  1. breaks it apart into all the slices (pieces) that don't have spaces (split),
  2. uses list comprehension to add on a random character to the end of each piece,
  3. joins them all back together (join),
  4. and finally takes off the one extra mask character at the end by slicing the resultant string (result[0:-1])

This solution uses the fact that strings are themselves iterables:

from collections.abc import Iterable
isinstance('hello', Iterable)

Result:
True

You don't need to convert strings to lists to pick out individual characters or to get their length; you can do this directly.

Putting that together in a function and letting you specify the character to replace as a bonus, you get:

import random

def swap_characters(string, character, mask):
    '''Replace all instances of a character from a string with a random sample from mask

    Parameters
    ----------
    string : str
        The string to be modified
    character : str
        The character to be replaced
    mask : str
        The string of characters from which to sample

    Returns
    -------
    str
        The modified string
    '''

    pieces = string.split(character)
    filled = [piece+random.choice(mask) for piece in pieces]
    result = ''.join(filled)
    return result[0:-1]

mask = '→☺☻♥♦♣♠•◘○§¶▬↨↑↓←∟↔'
example = "Let's take extra spaces. Here's 10:          "
x = swap_characters(example, ' ', mask)
print(x)

Result:
Let's☺take☻extra○spaces.↓Here's♦10:∟¶→↓→¶→

The reverse is a more common scenario with a variety of options. For example:

x = swap_characters(example, ' ', mask)
print(x)
for char in mask:
    x = x.replace(char, ' ')
print(x)

Result:
Let's↓take↓extra○spaces.☺Here's↓10:→¶↑§☻¶§§§¶§→→¶→↓
Let's take extra spaces. Here's 10:

Alternatively using regular expressions:

import re
x = swap_characters(example, ' ', mask)
print(x)
set = '|'.join(mask)
x = re.sub(set, ' ', x)
print(x)

Result:
Let's•take↓extra↔spaces.•Here's¶10:§•→→§¶→→→¶→↓
Let's take extra spaces. Here's 10:

英文:

A quick example:

import random 

mask = &#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;
original = &#39;The quick fox jumps over the lazy dog&#39;

pieces = original.split(&#39; &#39;)
filled = [piece+random.choice(mask) for piece in pieces]
result = &#39;&#39;.join(filled)
result = result[0:-1]

print(result)

Result:
The♥quick○fox∟jumps•over↨the∟lazy♠dog

This method takes your string and:

  1. breaks it apart into all the slices (pieces) that don't have spaces (split),
  2. uses list comprehension to add on a random character to the end of each piece,
  3. joins them all back together (join),
  4. and finally takes off the one extra mask character at the end by slicing the resultant string (result[0:-1])

This solution uses the fact that strings are themselves iterables:

from collections.abc import Iterable
isinstance(&#39;hello&#39;, Iterable)

Result:
True

You don't need to convert strings to lists to pick out individual characters or to get their length; you can do this directly.

Putting that together in a function and letting you specify the character to replace as a bonus, you get:

import random

def swap_characters(string, character, mask):
    &#39;&#39;&#39;Replace all instances of a character from a string with a random sample from mask

    Parameters
    ----------
    string : str
        The string to be modified
    character : str
        The character to be replaced
    mask : str
        The string of characters from which to sample

    Returns
    -------
    str
        The modified string
    &#39;&#39;&#39;

    pieces = string.split(character)
    filled = [piece+random.choice(mask) for piece in pieces]
    result = &#39;&#39;.join(filled)
    return result[0:-1]

mask = &#39;→☺☻♥♦♣♠•◘○&#167;&#182;▬↨↑↓←∟↔&#39;
example = &quot;Let&#39;s take extra spaces. Here&#39;s 10:          &quot;
x = swap_characters(example, &#39; &#39;, mask)
print(x)

Result:
Let&#39;s←take&#182;extra☻spaces.♣Here&#39;s↨10:↑↓∟◘&#167;☻↓☻↓◘

The reverse is a more common scenario with a variety of options. For example:

x = swap_characters(example, &#39; &#39;, mask)
print(x)
for char in mask:
    x = x.replace(char, &#39; &#39;)
print(x)

Result:
Let&#39;s↓take←extra&#182;spaces.☺Here&#39;s☺10:♠&#167;◘☻☺▬☺→&#182;←
Let&#39;s take extra spaces. Here&#39;s 10:

Alternatively using regular expressions:

import re
x = swap_characters(example, &#39; &#39;, mask)
print(x)
set = &#39;|&#39;.join(mask)
x = re.sub(set, &#39; &#39;, x)
print(x)

Result:
Let&#39;s•take&#182;extra↔spaces.○Here&#39;s↓10:♦↔∟♦◘♥••♣→
Let&#39;s take extra spaces. Here&#39;s 10:

huangapple
  • 本文由 发表于 2023年5月22日 09:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定