【问题标题】:Python string assignment issue!Python 字符串赋值问题!
【发布时间】:2011-08-17 07:45:15
【问题描述】:

所以我对 Python 还很陌生,但我完全不知道为什么这个强大的 oldUser 在我进行 parse 调用后会变为当前用户。任何帮助将不胜感激。

while a < 20:
    f = urllib.urlopen("SITE")
    a = a+1

    for i, line in enumerate(f):
        if i == 187:
            print line

            myparser.parse(line)
            if fCheck == 1:
                result  = oldUser[0] is oldUser[1]
                print oldUser[0]
                print oldUser[1]
            else:
                result = user is oldUser

            fCheck = 1
            print result

            user = myparser.get_descriptions(firstCheck)

            firstCheck = 1
            print user

            if result:
                print "SAME"
                array[index+1] = array[index+1] +0
            else:
                oldUser = user

        elif i > 200:
            break
        myparser.reset()

我不明白为什么结果也不起作用...我打印出两个值,当它们相同时,它告诉我它们不相等...另外,为什么 myparser.parse(line ) 将 oldUser 变成一个大小为 2 的数组?谢谢!

** 这是 myparse 的定义...

class MyParser(sgmllib.SGMLParser):
"A simple parser class."

def parse(self, s):
    "Parse the given string 's'."
    self.feed(s)
    self.close()

def __init__(self, verbose=0):
    "Initialise an object, passing 'verbose' to the superclass."

    sgmllib.SGMLParser.__init__(self, verbose)
    self.divs = []
    self.descriptions = []
    self.inside_div_element = 0

def start_div(self, attributes):
    "Process a hyperlink and its 'attributes'."

    for name, value in attributes:
        if name == "id":
            self.divs.append(value)
            self.inside_div_element = 1

def end_div(self):
    "Record the end of a hyperlink."

    self.inside_div_element = 0

def handle_data(self, data):
    "Handle the textual 'data'."

    if self.inside_div_element:
        self.descriptions.append(data)


def get_div(self):
    "Return the list of hyperlinks."

    return self.divs

def get_descriptions(self, check):
    "Return a list of descriptions."
if check == 1:
    self.descriptions.pop(0)
    return self.descriptions

【问题讨论】:

  • 发布您的所有代码。您发布的内容甚至无法运行。查看“fCheck”与“firstCheck”。

标签: python string parsing variable-assignment


【解决方案1】:

不要将字符串与is 进行比较。这会检查它们是否是同一个对象,而不是同一个字符串的两个副本。见:

>>> string = raw_input()
hello
>>> string is 'hello'
False
>>> string == 'hello'
True

另外,myparser 的定义也很有用。

【讨论】:

  • 啊啊啊我明白了……谢谢!但是你知道为什么说 user = myparse.get_descriptions() 也会改变 oldUser 吗? myparse.get_descriptions() 在 HTML 的 taht 行中返回我想要的用户名
【解决方案2】:

我不太确定您的代码在做什么,但我怀疑您想使用 == 而不是 is。使用is 比较对象身份,这与字符串相等性相同。两个不同的字符串对象可能包含相同的字符序列。

result = oldUser[0] == oldUser[1]

如果您好奇,有关is 运算符行为的更多信息,请参阅Python “is” operator behaves unexpectedly with integers

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多