如何自动替换INSIDE文本内容中的字符?

时间:2017-07-09 13:16:37

标签: python r text latex

我有一个包含许多乳胶表的文件夹/myfolder

我需要替换每个字符中的字符,即用minus -替换任何en dash符号

只是为了确定:我们正在替换该文件夹中所有tex文件的超级 INSIDE 。我不关心tex文件名。

手动执行此操作将是一场噩梦(文件太多,错误太多)。有没有办法自动循环文件并进行替换? Python / R中的解决方案会很棒。

谢谢!

5 个答案:

答案 0 :(得分:4)

sed -i -e 's/-/–/g' /myfolder/*应该有用。

e xpression执行 s earch g 并替换shell扩展的文件中的所有- {{ 1}}与/myfolder/*。 Sed会更改 i n位,即覆盖原始文件(您需要在MacOS上明确指定备份文件,但我无法记住该参数)。

绝对不关心是否是一个逐字连字符或乳胶语法的一部分。请注意这一点。

答案 1 :(得分:2)

尝试使用sed

find /home/milenko/pr -type f -exec \
sed -i 's/-/–/g' {} +
从命令行

(如果您使用的是Linux)

有关type

的更多信息

find utility -exec子句使用{}来表示匹配的文件。

答案 2 :(得分:2)

要重命名文件名,请使用

   allplayers = {
    "76561197979570214": {
        "clan": "FBÏ",
        "name": "phr",
        "observer_slot": 6,
        "team": "T",
    },
    "76561198156373160": {
        "clan": "ZOWIE",
        "name": "TOAO",
        "observer_slot": 7,
        "team": "T",
    },
    "76561198071702537": {
        "clan": "Team Biceps",
        "name": "snatchie",
        "observer_slot": 8,
        "team": "T",
    },
};

for(var key in allplayers){
    if(allplayers.hasOwnProperty(key)){
        if(allplayers[key].hasOwnProperty('name')){
          console.log(allplayers[key].name);
        }		
    }
}

它会将所有连字符重命名为短划线。

要将连字符中的所有内容替换为短划线,请使用

rename 's/-/–/g' *

答案 3 :(得分:1)

Python解决方案

import os
directory = os.getcwd()
for filename in os.listdir(directory):
  if "-" in filename:
    os.rename(os.path.join(directory,filename),os.path.join(directory,filename.replace("-","-")))

替换文件中的字符的新解决方案

u2212是减号的unicode字符,en-dash是u2014

import os
directory = os.getcwd()
import fnmatch

def _changefiletext(fileName):
  with open(fileName,'r') as file:
    str = file.read()
    str = str.decode("utf-8").replace(u"\u2212",u"\u2014").encode("utf-8")
  with open(fileName,'wb') as file:
    file.write(str)

# Filter the files on which you want to run the replace code (*.txt in this case)    

matches = []
for root, dirnames, filenames in os.walk(directory):
    for filename in fnmatch.filter(filenames, '*.txt'):
        matches.append(os.path.join(root, filename))

for filename in matches:
  print "Converting file %s" %(filename)
  _changefiletext(filename)

答案 4 :(得分:1)

首先,在删除代码中的“.bak”之前,先备份所有文件。我不想让你失去一些东西,或者如果我的剧本失火,我希望你能够重新创造你所拥有的东西。

其次,这可能不是很好的Python代码,因为我不是专家。但如果你在utf-8中进行编辑,它会起作用。因为短划线不是ASCII字符,所以直接替换不起作用。我承认我不太确定这里发生了什么,所以更大的python专家可能能够找出我能做得更好的地方。

#-*- coding: utf-8 -*-

import codecs
import glob
import re
import os

def replace_file(file):
    endash = "–".encode('utf-8')
    print ("Replacing " + file)
    temp = codecs.open("temp", "w", "utf-8")
    with codecs.open(file) as f:
        for line in f:
            line = re.sub("-", "–", line)
            temp.write(line)
    temp.close()
    f.close()
    os.system("copy temp \"" + file + ".bak\"")

x = glob.glob("*.tex")

for y in x:
    replace_file(y)
相关问题