首页 > 解决方案 > python中的输入()和\ n个字符

问题描述

我正在尝试使用 input() 查找并替换多个文件中的几行纯文本,但是当我输入 '\n' 字符来表示新行字符在文本中的位置时,它找不到它并且没有不要更换它。

我尝试使用 raw_strings 但无法让它们工作。

这是正则表达式的工作吗?

python 3.7

import os
import re
import time

start = time.time()
# enter path and check input for standard format
scan_folder = input('Enter the absolute path to scan:\n')
validate_path_regex = re.compile(r'[a-z,A-Z]:\\?(\\?\w*\\?)*')
mo = validate_path_regex.search(scan_folder)
if mo is None:
    print('Path is not valid. Please re-enter path.\n')
    import sys
    sys.exit()
os.chdir(scan_folder)
# get find/replaceStrings, and then confirm that inputs are correct.
find_string = input('Enter the text you wish to find:\n')
replace_string = input('Enter the text to replace:\n')
permission = input('\nPlease confirm you want to replace '
                   + find_string + ' with '
                   + replace_string + ' in ' + scan_folder
                   + ' directory.\n\nType "yes" to continue.\n')
if permission == 'yes':
    change_count = 0
    # Context manager for results file
    with open('find_and_replace.txt', 'w') as results:
        for root, subdirs, files in os.walk(scan_folder):
            for file in files:
                # ignore files that don't endwith '.mpr'
                if os.path.join(root, file).endswith('.mpr'):
                    fullpath = os.path.join(root, file)
                    # context manager for each file opened
                    with open(fullpath, 'r+') as f:
                        text = f.read()
                        # only add to changeCount if find_string is in text
                        if find_string in text:
                            change_count += 1
                        # move cursor back to beginning of the file
                        f.seek(0)
                        f.write(text.replace(find_string, replace_string))
        results.write(str(change_count)
        + ' files have been modified to replace '
        + find_string + ' with ' + replace_string + '.\n')
    print('Done with replacement')
else:
    print('Find and replace has not been executed')
end = time.time()
print('Program took ' + str(round((end - start), 4)) + ' secs to complete.\n')

查找字符串 = BM="LS"\nTI="12"\nDU="7" 替换字符串 = BM="LSL"\nDU="7"

原始文件看起来像

BM="LS"
TI="12"
DU="7" 

我希望它改为

BM="LSL"
DU="7" 

但文件没有改变。

标签: pythonpython-3.x

解决方案


因此,您的误解是source code之间的区别,它理解转义序列,如"this is a string \n with two lines",以及诸如“原始字符串”(在这种情况下没有意义的概念)之类的东西和您作为用户输入提供的数据。该input函数主要处理来自标准输入设备的数据。当您向标准输入提供数据时,它被解释为原始字节,然后该input函数假定它的意思是文本(使用您的系统设置暗示的任何内容进行解码)。允许用户输入换行符有两种方法,第一种是使用sys.stdin,但是,这将需要您提供 EOF,可能使用ctrl+ D

>>> import sys
>>> x = sys.stdin.read()
here is some text and i'm pressing return
to make a new line. now to stop input, press control d>>> x
"here is some text and i'm pressing return\nto make a new line. now to stop input, press control d"
>>> print(x)
here is some text and i'm pressing return
to make a new line. now to stop input, press control d

这不是很用户友好。您必须通过换行符和EOF,即return++或 do ctrl+两次,这取决于系统,我相信。DctrlD

更好的方法是允许用户输入转义序列,然后自己解码:

>>> x = input()
I want this to\nbe on two lines
>>> x
'I want this to\\nbe on two lines'
>>> print(x)
I want this to\nbe on two lines
>>> x.encode('utf8').decode('unicode_escape')
'I want this to\nbe on two lines'
>>> print(x.encode('utf8').decode('unicode_escape'))
I want this to
be on two lines
>>>

推荐阅读