1
나는 폴더 내의 모든 XML 파일에서 특정 노드의 텍스트 내용을 추출해야하는 Python (3) XML 파서를 연구 중이다. 그런 다음 스크립트는 수집 된 데이터를 탭으로 구분 된 텍스트 파일에 작성해야합니다. 지금까지 모든 기능이 작동하는 것 같습니다. 스크립트는 첫 번째 파일에서 원하는 모든 정보를 반환하지만 두 번째 파일을 구문 분석하기 시작할 때 항상 중단됩니다.파이썬 XML 파서가 첫 번째 파일 다음에 깨지는 이유는 무엇입니까?
중단되면 "TypeError : 'str'개체를 호출 할 수 없습니다."를 반환합니다. 두 번째 파일을 확인한 결과 첫 번째 파일을 폴더에서 제거 할 때 첫 번째 파일과 마찬가지로 기능이 작동한다는 것을 알았습니다. 저는 Python/XML을 처음 접했습니다. 모든 조언, 도움 또는 유용한 링크가 크게 감사하겠습니다. 감사!
import xml.etree.ElementTree as ET
import re
import glob
import csv
import sys
content_file = open('WWP Project/WWP_texts.txt','wt')
quotes_file = open('WWP Project/WWP_quotes.txt', 'wt')
list_of_files = glob.glob("../../../Documents/WWPtextbase/distribution/*.xml")
ns = {'wwp':'http://www.wwp.northeastern.edu/ns/textbase'}
def content(tree):
lines = ''.join(ET.tostring(tree.getroot(),encoding='unicode',method='text')).replace('\n',' ').replace('\t',' ').strip()
clean_lines = re.sub(' +',' ', lines)
return clean_lines.lower()
def quotes(tree):
quotes_list = []
for node in tree.findall('.//wwp:quote', namespaces=ns):
quote = ET.tostring(node,encoding='unicode',method='text')
clean_quote = re.sub(' +',' ', quote)
quotes_list.append(clean_quote)
return ' '.join(str(v) for v in quotes_list).replace('\t','').replace('\n','').lower()
def pid(tree):
for node in tree.findall('.//wwp:sourceDesc//wwp:author/wwp:persName[1]', namespaces=ns):
pid = node.attrib.get('ref')
return pid.replace('personography.xml#','') # will need to replace 'p:'
def trid(tree): # this function will eventually need to call OT (.//wwp:publicationStmt//wwp:idno)
for node in tree.findall('.//wwp:sourceDesc',namespaces=ns):
trid = node.attrib.get('n')
return trid
content_file.write('pid' + '\t' + 'trid' + '\t' +'text' + '\n')
quotes_file.write('pid' + '\t' + 'trid' + '\t' + 'quotes' + '\n')
for file_name in list_of_files:
file = open(file_name, 'rt')
tree = ET.parse(file)
file.close()
pid = pid(tree)
trid = trid(tree)
content = content(tree)
quotes = quotes(tree)
content_file.write(pid + '\t' + trid + '\t' + content + '\n')
quotes_file.write(pid + '\t' + trid + '\t' + quotes + '\n')
content_file.close()
quotes_file.close()
감사합니다. miah! 확실히 시작되었습니다. 이제는 더 많은 파일을 파싱하지만 전부는 아닙니다. 'TypeError : 'NoneType'객체를 str 암시 적으로 변환 할 수 없습니다. ' 아마도 파일 중 하나가 나머지 파일을 따르지 않고 스크립트를 위반하고있는 것입니까? – Bill
어떤 데이터도 보지 않고,'get_ *'함수 중 하나의 반환 값은'None'이므로, 내용이나 따옴표 파일에 쓰려고 할 때 실패합니다. 나는 그것들을 시도 할 때 파일의 이름을 출력 해 줄 것이므로 실패한 파일을 볼 수있다. – miah
그건 완벽하게 작동했습니다, 미아. 도와 주셔서 다시 한 번 감사드립니다! – Bill