【问题标题】:Encoding accented/dotted characters in python?在python中编码重音/点字符?
【发布时间】:2015-08-29 00:05:18
【问题描述】:

我正在尝试制作一个随机字符串生成器,它可以生成长度为 min

我的输入:a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣ 5 10

from random import *
#Class random generator
#@variables list aList,boolean again, int maximum, int minimum
class randomStringGenerator:
    def __init__(this):
        aList = []
        allowed = input("What are the characters that you will allow?\n" +
                        "Please press the chracters you want and leave a space between each character\n, then enter to submit\n" +
                        "e.g. 'a' 'b' 'c'\n ")
        aList = allowed.split(" ")
        minimum = input("What is the minimum number of characters in the string that you want? \n")
        maximum = input("What is the maximum number of characters in the string that you want? \n")
        this.aList = aList
        this.minimum = int(minimum)
        this.maximum = int(maximum)
        again = True
        this.again = again
    #generateRandNum generates a random int from a minimum to b maximum
    #@param this,mini,maxi
    #@return int x the integer that was chosen
    def generateRandNum(this,mini,maxi):
        x = randint(mini,maxi)
        return x
    #generateRandString generates the actual string randomly

    def generateRandString(this):
        ans = ""
        strSize = this.generateRandNum(this.minimum,this.maximum)
        pos = 0
        while(pos < strSize):
            size = len(this.aList)
            idx = this.generateRandNum(0,size - 1)
            char = this.aList[idx]
            ans = ans + char
            pos += 1
            ans.encode('utf-8')
            print(ans)
    def getAgain(this):
        return this.again
    def replay(this):
        x = input("Would you like to generate another string using the same settings? y/n \n")
        if(x == "y"):
            this.generateRandString()
        else:
            y = input("Would you like to generate another string using different settings? y/n \n")
            if(y == "y"):
                new = input("What are the new characters that you will allow? ")
                mini = input("What is the new minimum number of characters? ")
                maxi = input("What is the new maximum number of characters? ")
                this.aList = new.split(" ")
                this.minimum = int(mini)
                this.maximum = int(maxi)
                this.generateRandString()
            else:
                this.again = False
s = randomStringGenerator()
s.generateRandString()
while(s.getAgain()):
    s.replay()

示例输出:如您所见,我将最少字符设置为 5 个,但只显示 2 个,并且由于某种原因多次打印...

What are the characters that you will allow?
Please press the chracters you want and leave a space between each character
, then enter to submit
e.g. 'a' 'b' 'c'
 a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣
What is the minimum number of characters in the string that you want? 
5
What is the maximum number of characters in the string that you want? 
10
o
oḅ
oḅ
oḅ
oḅ
oḅ
oḅ

【问题讨论】:

  • 是 Python2.7 还是 Python3.x? unicode 是 Python3.x 的默认编码系统,因此编码不太可能成为问题。对于Python2.7,在开头添加from __future__ import unicode_literals。如果脚本中有非 unicode 字符,请将 # -*- coding: utf-8 -*- 添加到代码的最顶部。
  • Python 3,但由于某种原因,除非我使用 .encode 方法,否则它无法正确显示在我的代码中
  • 没关系,你是对的。字数没有达到限制的问题仍然是个问题。
  • 你的意图是什么?对我来说,generateRandString 中的代码只是获取一个从 5 到 10 的随机数,然后生成一个该长度的字符串,您的代码似乎做得对。

标签: python unicode utf


【解决方案1】:

您的代码中有几个问题。

  1. 在 python 中使用self 而不是this
  2. 在您的程序中添加if __name__ == "__main__"
  3. 使用编码encoding: utf-8 指定编码。
  4. 将获取输入操作定义为函数_prepare()

更新后的代码如下:

#encoding:utf-8
from random import *

class randomStringGenerator:
    def __init__(self):
        self.aList = []
        self.again = True
        self._prepare()

    def _prepare(self):
        allowed = input("What are the characters that you will allow?\n"
                        "Please press the chracters you want and leave a space between each character\n, then enter to submit\n"
                        "e.g. 'a' 'b' 'c'\n")
        aList = allowed.split(" ")
        minimum = input("What is the minimum number of characters in the string that you want? \n")
        maximum = input("What is the maximum number of characters in the string that you want? \n")
        self.aList = aList
        self.minimum = int(minimum)
        self.maximum = int(maximum)

    def generateRandNum(self, mini, maxi):
        x = randint(mini,maxi)
        return x

    def generateRandString(self):
        ans = u""
        strSize = self.generateRandNum(self.minimum, self.maximum)
        pos = 0
        while(pos < strSize):
            size = len(self.aList)
            idx = self.generateRandNum(0, size - 1)
            char = self.aList[idx]
            ans = ans + char
            pos += 1
            ans.encode('utf-8')
        return ans

    def getAgain(self):
        return self.again

    def replay(self):
        x = input("Would you like to generate another string using the same settings? y/n \n")
        if(x == "y"):
            return self.generateRandString()
        else:
            y = input("Would you like to generate another string using different settings? y/n \n")
            if(y == "y"):
                self._prepare()
                return self.generateRandString()
            else:
                self.again = False
                return ""

if __name__ == "__main__":
    s = randomStringGenerator()
    print (s.generateRandString())
    while(s.getAgain()):
        print (s.replay())

输出如下:

python3 str_1.py 
What are the characters that you will allow?
Please press the chracters you want and leave a space between each character
, then enter to submit
e.g. 'a' 'b' 'c'
a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣
What is the minimum number of characters in the string that you want? 
5
What is the maximum number of characters in the string that you want? 
10
bpjwdsndv
Would you like to generate another string using the same settings? y/n 
y
radsṛreyrx
Would you like to generate another string using the same settings? y/n 
n
Would you like to generate another string using different settings? y/n 
y
What are the characters that you will allow?
Please press the chracters you want and leave a space between each character
, then enter to submit
e.g. 'a' 'b' 'c'
a ä æ e i ï o u ü b ḅ d ḍ f v h ḥ k g l ľ m y n ṇ p ṕ r ṛ s j w ẉ x x̣
What is the minimum number of characters in the string that you want? 
5
What is the maximum number of characters in the string that you want? 
8
dnṛnhṛv
Would you like to generate another string using the same settings? y/n 
n
Would you like to generate another string using different settings? y/n 
n

【讨论】:

  • 在Python3中,没有raw_input
  • 谢谢!在 Java 和 Python 之间切换有时会让我感到困惑,我不小心开始使用“this”而不是“self”。
猜你喜欢
  • 2020-11-28
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多