[英]Reading line by line the data from an XML file
我試圖找到一個包含http或//或\\的鏈接,並在找到后用href標記包圍,但是當從xml讀取的數據逐行讀取時。我看到輸出是每個字母都分開的。參見下面的輸入和輸出。.有人可以建議我要去哪里錯嗎?
INput:-http://pastebin.com/p9H8GQt4
Currentoutput:- http://pastebin.com/7428jK63
sanity_results = sanity_results.replace('\n','<br>\n')
return sanity_results
def main ():
resultslis=[]
xmlfile = open('results.xml','r')
contents = xmlfile.read()
testresults=getsanityresults(contents)
#print testresults
for line in testresults:
#print line
line = line.strip()
#print line
line = re.sub(r'(http://[^\s]+|//[^\s]+|\\\\[^\s]+)', r'<a href="\1">\1</a>', line)
print line
resultslis.append(line)
print resultslis
if __name__ == '__main__':
main()
您想使用XML解析器,例如
等用於解析任何類型的XML文件。 自己解析XML-特別是逐行是容易出錯的。 特別是正則表達式的使用是按設計破壞的。 不要那樣做
聰明一點,改用XML分析器。
您正在遍歷字符串,而不是遍歷文件。
如果要遍歷字符串中的行,請使用str.splitlines
:
>>> text ='''first
... second
... '''
>>> for line in text.splitlines():
... print(line)
...
first
second
>>> for char in text:
... print(char)
...
f
i
r
s
t
s
e
c
o
n
d
無論如何,我建議您使用XML解析器。 stdlib
已經提供了一個,周圍還有很多其他的庫。
問題是這一行:
contents = xmlfile.read()
返回一個字符串; 因此,迭代操作針對字符。 用readlines()代替read(),就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.