【问题标题】:Python3: Unable to split word from parsed dataPython3:无法从解析的数据中拆分单词
【发布时间】:2018-12-13 17:15:52
【问题描述】:

我正在创建一个 MapReduce 作业以从 XML 文件中查找“ArticleTitle”。我正在使用 mapper.py 来识别标签并根据字母拆分它。 以下是脚本:

tree = ET.parse('File location')
doc = tree.getroot()
for ArticleTitle in doc.iter('ArticleTitle'):
    file1 = (ET.tostring(ArticleTitle, encoding='utf8').decode('utf8'))
    filename = file1[52:(len(file1))]
    Article_Title= filename.split("<")[0]
    # print(Article_Title)
    for line in Article_Title:
        line_1= re.findall(r"\w+|[^\w\s]", line, re.UNICODE)
        print(line_1)

我得到的输出是:

['T']['h']['e'][]['e']['f']['f']['e']['c']['t'][]['o']['f']

但是,我希望输出是:

['The', 'effect', 'of', 'Hene', 'laser']

【问题讨论】:

  • 你为什么使用正则表达式而不是 xml 解析器?
  • 文章标题是一个字符串。如果你遍历一个字符串,你会得到单个字符。如果您想要整个单词,则不需要循环 - 只需执行 Article_Title.split()
  • @KuboMD 让它成为答案。
  • @TheIncorrigible1 我已经使用 ElementTree 来解析数据,只是我需要从我发现问题的解析数据中映射单词
  • 好的,谢谢你的提议 :)

标签: python python-3.x xml-parsing mapreduce


【解决方案1】:

Article Title 是一个字符串。见:

Article_Title= filename.split("<")[0]

如果你遍历一个字符串,你会得到单个字符。

for i in "hello!":
    print(i)

>>>>h
>>>>e
>>>>l
>>>>l
>>>>o
>>>>!

如果您想要整个单词,则不需要循环 - 只需 Article_Title.split()

"The effect of Hene laser" --> ['The', 'effect', 'of', 'Hene', 'laser']

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多