在Python中生成随机的汉字字符串

时间:2015-08-05 19:43:23

标签: python chinese-locale

我写了一小段代码,在App Store中搜索三个字母的随机字符串:

searchTerm = (''.join(random.choice(string.ascii_lowercase) for i in range(3)))
    urllib.urlretrieve("https://itunes.apple.com/search?country=us&entity=software&limit=5&term=" + str(searchTerm), "download.txt")

现在我想知道我怎么能这样做,但是有中文字符,因为我也想探索中文App Store。

我看了一下这个问题making a list of traditional Chinese characters from a string,但它没有帮助。

1 个答案:

答案 0 :(得分:0)

什么是汉字很复杂,请参阅What's the complete range for Chinese characters in Unicode?

您可以选择适合您情况的Unicode范围:

#!/usr/bin/env python2
import random
import urllib

common, rare = range(0x4e00, 0xa000), range(0x3400, 0x4e00)
chars = map(unichr, rare + common)
random_word = u''.join([random.choice(chars) for _ in range(3)]) # 3 letters
search_term = urllib.quote(random_word.encode('utf-8'), safe='')
path, headers = urllib.urlretrieve("https://itunes.apple.com/search?"
    "country=cn&entity=software&limit=5&term=" + search_term,
    u"download%s.json" % random_word)

您可能希望data = json.load(urllib2.urlopen(url))而不是将响应保存到文件中。