![](/img/trans.png)
[英]What's the best way to generate random strings of a specific length in Python?
[英]Generate random strings from list with specific length in csv
我想從這個符號列表中隨機 select 一串字符而不替換:'@','+','?',',','$','*','%','#', '}','>','&'.'^'.
生成的字符串的長度將等於 csv 中另一列中的單詞的長度。
現有 csv 示例:
Word Length
dog 3
wolf 4
cactus 6
bus 3
我希望有這樣的代碼,它將第三列附加到現有的 csv 文件中,生成的字符串的每個單詞的長度相等。 這是我想要的結果的一個例子:
Word Length String
dog 3 @!#
wolf 4 &*%!
cactus 6 ^?!@#%
bus 3 }&^
這是我嘗試過的代碼,但我認為它不正確。
import random
import pandas as pd
import os
cwd = os.getcwd()
cwd
os.chdir("/Users/etcetc") #change directory
df = pd.read_csv('generatingstring.csv')
list1 = ['@','+','?','!','$','*','%','#','}','>','&','^']
list2 = df['String'] #creating a new column for the generated string
for row in df['Length']: #hope this reads each row in that column
for n in range(1, row): #hope this reads the length value within cell
s = random.choice(list1)
list1.remove(s) #to ensure random selection without replacement
list2.append(s)
我希望讓它讀取 Length 列中的每一行,並在每一行中記下隨機 select 的符號數。
謝謝!
你可以試試
import numpy as np
df.Word.map(lambda x : ''.join(np.random.choice(list1,len(x),replace = False)))
Out[145]:
0 &$!
1 >^$!
2 @}%?$>
3 #+!
Name: Word, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.