2015-11-26 49 views
0

我是这个论坛的新手(这是我的第一个问题),所以请耐心等待。我正在用瑞典语拼出一个网站。它使用ISO-8859-1字符集。python中的瑞典Unicode问题

在源可能是这个样子:

<div class="fl icon-post-old"></div> 
    2015-11-13, 15:09 
    <a href=" 

比方说,我想抓住的日期和时间(这是不是一个真实的例子)。

threadcode=opener.open(threadurl).read() 
threadcode2=threadcode.decode("ISO-8859-1") 
post=re.findall(r'<div class="fl icon-post-old"></div>(.*?)<a',str(threadcode2)) 
post2=re.findall(r'<div class="fl icon-post-old"></div>(.*?)<a',str(threadcode)) 
print (post) #this is blank 
print (post2) #this works fine 

所以,如果我寻找的“好可读瑞典可变后”的东西,它似乎并没有工作。但是,如果我使用Unicode表示进行相同的搜索(这不是很有用),那么相同的搜索就会起作用。

你们中的任何一位不错的程序员谁知道这里发生了什么?

我还可以增加,如果有帮助,在某些情况下,搜索实际工作... 例如:

post=re.findall(r'Jag vill(.*?)bil',str(threadcode2)) 

这将工作...

我很迷茫。

+0

你的字符串必须是unicode字符串,这里是一个很好的出发点:http://stackoverflow.com/questions/1327731/python-problems-with-regular-expression-and-unicode – schwobaseggl

回答

1

传递unicode字符串到re.findall时,您应该通过re.UNICODE标志:

post=re.findall(r'<div class="fl icon-post-old"></div>(.*?)<a',threadcode2, flags=re.UNICODE) 
+0

'str(threadcode2)''打电话有点败了使用unicode的全部... –

+0

哦,你是对的 - 我的意思是消除这一点。 – babbageclunk

1

无关,与瑞典。我认为re是在多线路上运行。如果你这样做:

post=re.findall(
    r'<div class="fl icon-post-old"></div>(.*?)<a', 
    threadcode2.replace('\n','') 
) 

你会得到预期的结果。

+0

谢谢!谢谢大家回答。它原来是一个多线问题... – cbroxe