【问题标题】:how to edit txt file with regular expressions (re) in python如何在 python 中使用正则表达式 (re) 编辑 txt 文件
【发布时间】:2022-11-24 03:39:59
【问题描述】:

我在 python 上编辑 txt 文件时遇到问题。

嗨,大家好,

我在 python 上编辑 txt 文件时遇到问题。

这是txt文件的前几行

m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance']
m1 +++$+++ 1492: conquest of paradise +++$+++ 1992 +++$+++ 6.20 +++$+++ 10421 +++$+++ ['adventure', 'biography', 'drama', 'history']

这是我的代码:

import re

file = open('datasets/movie_titles_metadata.txt')

def extract_categories(file):

    for line in file:
        line: str = line.rstrip()
        if re.search(" ", line):
            line = re.sub(r"[0-9]", "", line)
            line = re.sub(r"[$ + : . ]", "", line)
            return line
        
      
    
extract_categories(file) 

我需要得到一个看起来像这样的输出:

['action', 'comedy', 'crime', 'drama', 'thriller'] 有人可以帮忙吗?

【问题讨论】:

    标签: python python-re txt


    【解决方案1】:

    正则表达式不是正确的解决方案。您的每个列表都在每一行的末尾,因此请使用str.rsplit

    from io import StringIO
    import ast
    
    content = """m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance']
    m1 +++$+++ 1492: conquest of paradise +++$+++ 1992 +++$+++ 6.20 +++$+++ 10421 +++$+++ ['adventure', 'biography', 'drama', 'history']"""
    
    # this is a mock file-handle, use your file instead here
    with StringIO(content) as fh:
        genres = []
    
        for line in fh:
            _, lst = line.rsplit('+++$+++', 1)
            lst = ast.literal_eval(lst.strip())
            genres.extend(lst)
    
    print(genres)
    ['comedy', 'romance', 'adventure', 'biography', 'drama', 'history']
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2012-05-08
      • 2023-02-07
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多