Как заменить первую строку файла, используя Python или другие инструменты? - PullRequest
0 голосов
/ 06 ноября 2018

У меня есть файл с именем hanlp.properties:

root=/Users/pan/Documents
other content

Я хочу передать параметр "/ User / a / b" и заменить корневой путь

root=/User/a/b
other content

/User/a/b - это параметр.

Как достичь этой цели с помощью Python или любых других инструментов?

Ответы [ 5 ]

0 голосов
/ 17 ноября 2018

начиная с HanLP v1.7, вы можете использовать множество подходов, отличных от файла конфигурации, для установки рута. См. эту проблему , вам может понадобиться переводчик Google.

0 голосов
/ 07 ноября 2018

пишу оболочку a.sh

if [ ! -n "$1" ] ;then
   echo "Please input hanlp data path!"
else
   echo "The hanlp data path you input is $1"
   var="root="
   path=$var$1
   sed -i '/^root/c'$path'' hanlp.properties
fi

тогда

 chmod 777 a.sh

пробег:

./a.sh /User/a/b
0 голосов
/ 06 ноября 2018

Использование Python 3:

import argparse

from sys import exit

from os.path import getsize

# collect command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--parameter', required=True, type=str)
parser.add_argument('-f', '--file', required=True, type=str)
args = parser.parse_args()

# check if file is empty
if getsize(args.file) == 0:
    print('Error: %s is empty' % args.file)
    exit(1)

# collect all lines first
lines = []
with open(args.file) as file:
    first_line = next(file)

    # Check if '=' sign exists in first line
    if '=' not in first_line:
        print('Error: first line is invalid')
        exit(1)

    # split first line and append new line
    root, parameter = first_line.split('=')
    lines.append('%s=%s\n' % (root, args.parameter))

    # append rest of lines normally
    for line in file:
        lines.append(line)

# rewrite new lines back to file
with open(args.file, 'w') as out:
    for line in lines:
        out.write(line)

Что работает следующим образом:

$ cat hanlp.properties
root=/Users/pan/Documents
other content
$ python3 script.py --file hanlp.properties --parameter /Users/a/b
$ cat hanlp.properties
root=/User/a/b
other content
0 голосов
/ 06 ноября 2018

Это может помочь вам.

import os
infile=os.path.join(os.getcwd(),"text.txt")
data = open(infile).readlines()
print(data)
data[0] = 'new content of;lkdsajv;ldsahbv;ikj'+'\n'
print(data)
with open(infile, 'w') as fw:
    fw.writelines(data)
0 голосов
/ 06 ноября 2018

РЕДАКТИРОВАТЬ: , поскольку OP изменил требование, поэтому добавление этого решения теперь тоже. проверил это с GNU awk. Добавьте > temp_file && mv temp_file Input_file на случай, если вы хотите сохранить вывод в самом файле Input_file.

awk -F'=' 'FNR==NR{if($0~/root/){value=$2};nextfile} /root/{$2=value} 1' OFS="=" parameter_file  Input_file

Объяснение: Добавление пояснения к приведенному выше коду тоже здесь.

awk -F'=' '                           ##Mentioning field separator as = here for all lines of all mentioned passed Input_files to awk.
FNR==NR{                              ##Checking condition FNR==NR which will be TRUE when parameter_file is being read.
  if($0~/root/){                      ##Checking if a line has root string in it then do following.
    value=$2                          ##Assigning value of $2 to variable value here.
  }
  nextfile                            ##nextfile will jump to next passed Input_file and all further lines for parameter file will be skipped.
}
/root/{                               ##Checking if a line has string root in it then do following.
  $2=value                            ##Setting 2nd field value as value variable here.
}
1                                     ##By mentioning 1 telling awk to print edited/no-edited lines here.
' OFS="=" parameter_file  Input_file  ##Mentioning OFS value as = here and mentioning Input_file(s) name here.


Это должна быть простая sed программа. Используйте параметр sed -i на случай, если вы хотите сохранить вывод в самом файле Input_file.

sed '/root=/s/path1/path2/' Input_file

Если вы хотите использовать awk, вам может помочь следующее.

awk '/root=/{sub("path1","path2")} 1' Input_file > temp_file && mv temp_file Input_file
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...