python - 如何使用python读取文件?

标签 python regex python-2.7

我正在阅读上面的 .txt 文件,其中我必须识别这三个字母的单词(ARW、CZC、DUN 等)。后来我必须读取测试用例 ID,例如 VR-GREQ...,直到下一种语言。但我在读取这个 .txt 文件时遇到问题。 下面是我的代码:

with open(output_filename) as parser_file:
        for language in parser_file:
            language = language.strip()
            if(re.search('[A-Z]', language)):
                lines = parser_file.readlines()

我必须进一步编码,有人可以帮助我吗?

我的新代码: 输出文件名 = r"C:\Usersktop\TEST\Language\Output.txt" def 写作():

    rx = r'^([A-Z]{3})$'

# define a dictionary for the languages
    languages = {}
    # looks for exactly three uppercase letters from beginning to end

    # define a temporary list
    tmp = list()
    for line in open(output_filename, 'r+'):
        m = re.search(rx, line, re.MULTILINE)
        if m is not None:
            if len(tmp) > 0:
                languages[current] = tmp
            tmp = list()
            current = m.group(1) # current holds the actual language tag
        else:
            if len(line) > 0:
                tmp.append(line.strip())

    # after the loop
    if len(tmp) > 0:
        languages[current] = tmp
    print languages

最佳答案

如果您需要查找长度为 3 的字符串,请使用 [A-Z]{3}。您可以根据这 3 个字符“单词”的位置将整个列表拆分为数组。

编辑:回答您的评论...

headers=re.split('[A-Z]{3}\n',YOUR_STRING) 将查找每个部分的“标题”。 然后你可以执行 NEW_STRING=YOUR_STRING[YOUR_STRING.find(headers[0]):YOUR_STRING.find(headers[1])]

使用循环和其他工具,这应该可以帮助您实现您的目标。

关于python - 如何使用python读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35465407/

相关文章:

python - 如何通过删除不必要的字段来扩展评论框架(django)?

python - 如何在列表中找到最常见的元素,如果有平局,最后一次出现的是第一个?

regex - Groovy 正则匹配引号之间的所有内容

python - 如何为 "not"、 "no"和 "never"之后的字符串中的否定词添加标签

python - 如果发生异常则停止 task.LoopingCall

python - 这是一个对象还是一个函数?

javascript - 用 javascript 对象替换字符串值

python - 如何在 Pandas 中的 "day period"上覆盖数据以进行绘图

python - 在笔记本内扩展无法按预期工作

python-2.7 - 使用 pyopenssl 创建自签名证书