Python 在文件中查找、替换或添加字符串

标签 python search encoding replace

您好,感谢您的关注:)

我有一个超过 2500 行的文本图 block ,每行包含有关视频文件的信息。其中一个标签(可以这么说)用于观看状态,我正在寻找一种将其从一个值更改为另一个值的方法,或者如果未设置则添加新值。下面的代码可以工作,但它必须为每个搜索值打开和关闭文件,这意味着它非常慢。任何人都可以建议一种打开文件一次并一次性完成所有搜索的方法吗?

谢谢

for x in y:
    print '    --> ' + x['title'].encode('utf-8')

    searchValue = x['movieid']
    addValue = "\t_w\t1\t"
    checkvalue = "\t_w\t0\t"
    for line in fileinput.input(file, inplace=1):
        if searchValue in line:
            if checkvalue in line:
                line = line.replace(checkvalue, addValue)
            elif not addValue in line:
                line = line + addValue
        sys.stdout.write(line)

这就是我的最终结果,感谢大家的意见。

    myfile_list = open(file).readlines()
    newList = []
    for line in myfile_list:
        for x in y:
            if x['movieid'] in line:
                print '    --> ' + x['title'].encode('utf-8')
                if checkvalue in line:
                    line = line.replace(checkvalue, addValue)
                elif not addValue in line:
                    line = line.replace('\n', addValue+'\n')
        newList.append(line)
    outref = open(file,'w')
    outref.writelines(newList)
    outref.close()

编辑 我遇到了编码问题,该文件以 utf-8 编码,但在搜索值为 时出错或找不到匹配项

'Hannibal - S01E01 - Ap\xe9ritif.mkv'

文件中的匹配行看起来像

_F  /share/Storage/NAS/Videos/Tv/Hannibal/Season 01/Hannibal - S01E01 - Apéritif.mkv    _rt 43  _r  8.4 _s  1   _v  c0=h264,f0=24,h0=720,w0=1280    _IT 717ac9d _id 1671    _et Apéritif    _DT 7142d53 _FT 7142d53 _A  4212,4211,2533,4216 _C  T   _G  j|d|h|t _R  GB:TV-MA    _T  Hannibal    _U   thetvdb:259063 imdb:tt2243973  _V  HDTV    _W  4210    _Y  71  _ad 2013-04-04  _e  1   _ai Apéritif    _m  1117

我尝试过 codecs.open 和decode().encode() 选项,但总是出错,我相信行中的重音字母是问题所在,因为它可以执行 if searchValue 行: 如果该行没有重音字母。这是我目前正在尝试的方法,但我对其他方法持开放态度。

if os.path.isfile("/share/Apps/oversight/index.db"):
    newfile = ""
    #searchValueFix = searchValue.decode('latin-1', 'replace').encode('utf8', 'replace')
    #print searchValueFix
    #print searchValue
    addValue = "\t_w\t1\t"
    replacevalue = "\t_w\t0\t"
    file = open("/share/Apps/oversight/index.db", "r")
    for line in file:
        if searchValue in line:
            if replacevalue in line:
                line = line.replace(replacevalue, addValue)
            elif not addValue in line:
                line = line.replace(searchValue+"\t", searchValue+addValue)
        newfile = newfile + line
    file.close()
    file = open("/share/Apps/oversight/index.db", "w")
    file.write(newfile)
    file.close()
    newfile = ""

最佳答案

与PyNEwbie提出的方法类似,可以1行1行写:

myfile_list = open(file).readlines()
outref = open(myfile, 'w')
for line in myfile_list:
    # do something to line
    outref.write(line)

outref.close()

关于Python 在文件中查找、替换或添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18149398/

相关文章:

python - 分类变量 pandas

search - 爬虫如何确保最大覆盖率?

vb.net - Outlook ReportItem.Body返回某些用户的困惑编码

PHP fputcsv编码

python - 每次调用函数时,Tkinter 比例都会卡住

python - 根据一组特定的单词拆分字符串

python - 根据用户输入创建对象

python - 如何使用关键字从 txt 文件中搜索和检索整行

C++ 递归问题 <confused>

python - 如何确定 CSV 文件的编码?