# -*- coding: utf-8 -*-
import codecs # To write UTF-8 characters to a file
import random
# Assemble data list
letters = [u'அ', u'ம', u'த']
data = [] # This list will hold the shuffled data
for current_letter in letters:
# Choose how many times to repeat the current letter.
times_repeated = random.choice([20, 30, 40])
data.extend([current_letter] * times_repeated)
# Now, shuffle the 'data' list
random.shuffle(data)
# Now write the shuffled list to a file as one continuous string
data_string = "".join(data)
with codecs.open("data.txt", "w", "utf-8") as f:
f.write(data_string)
>>> from random import shuffle
>>> my_string = list('This is a test string.')
>>> shuffle(my_string)
>>> scrambled = ''.join(my_string)
>>> print(scrambled)
.sTtha te s rtisns gii
>>> from random import random
>>> my_string = 'This is a test string.'
>>> scrambled = sorted(my_string, key=lambda i: random())
>>> scrambled = ''.join(scrambled)
>>> print(scrambled)
ngi rts ithsT.staie s
你也不需要这个。来自sorted文档:
Return a new sorted list from the items in iterable.
归功于我的朋友@AswinMurugesh,他帮助我编写了代码。在
下面的代码做到了这一点。在
我建议把这个问题分成三个部分:把你的字母表整理一下,然后把它写进一个文件里。请注意,下面代码中的第一行应该位于python文件的顶部,以允许您在源代码中使用utf-8字符。在
请注意,如果您知道希望每个字母出现多少次,您可以将这些信息放入字典中,而不是从
^{pr2}$[20, 30, 40]
中随机选择:你可以用很多方法来解决这个问题。最有效的方法是使用^{} module 。在
^{}
为此,您必须从字符串的字符中创建一个
^{bq}$list
,因为字符串是immutable。在^{}
^{pr2}$您不必为此创建
list
;因为根据random.sample
文档:The ^{} built-in 带{a6}
你也不需要这个。来自
sorted
文档:因为在Python中,字符串被视为iterable(见下文),因此可以对其使用
sorted
。在iterable定义为
相关问题 更多 >
编程相关推荐