简体   繁体   English

如何通过不触摸 python 中文本文件的每一行中该单词的 rest 来替换每行中的第一个特定特殊字符

[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python

How to replace the first word in a series of occurrences like below.如何替换一系列出现中的第一个单词,如下所示。

Im trying to replace the first "/" in each line(if present) with a "", if not present, go to the next line in a text file.我试图用“”替换每行(如果存在)中的第一个“/”,如果不存在,go 到文本文件的下一行。

ex: in.txt例如:in.txt

Stackover flow /abc/one/two
is suitable to search three/four/five
answers for all /six/seven/eight

output like: output 喜欢:

Stackover flow abc/one/two
is suitable to search three/four/five
answers for all six/seven/eight

I have tried re.sub with various combinations but not able to get any suitable answers.我已经尝试了各种组合的 re.sub,但无法得到任何合适的答案。 I hope to find answers here.我希望在这里找到答案。 Thanks in advance.提前致谢。

You can split the string with "/" and join again ignoring the first split.您可以使用“/”拆分字符串并再次加入忽略第一个拆分。

split = _str.split("/")
_new_str = split[0]+"/".join(split[1:])

If I understand the question correctly, you only try to change the first '/' when it's at the beginning of some list of options, eg '/abc/def/ghi', but not when it is between words, eg 'abc/def/ghi'.如果我正确理解了这个问题,您只尝试更改位于某些选项列表开头的第一个“/”,例如“/abc/def/ghi”,而不是在单词之间,例如“abc/”定义/ghi'。

This replaces '/' only if they are at the beginning of a word (per your example):仅当它们位于单词的开头时才会替换“/”(根据您的示例):

import re    

with open('in.txt', 'r') as input_file, open('out.txt', 'w') as output_file:
    for row in input_file:
        new_row = re.sub('\s/', ' ', row)
        output_file.write(new_row)

If you want to change the original file, I will refer you here which is quite a nice explanation of why it is not a good idea.如果您想更改原始文件,我会在这里向您推荐,这很好地解释了为什么这不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 替换文件 python 中每一行的第一个字符 - replace first character of each line in file python "将第一个文件中包含特定单词的每一行替换为第二个文件中的行" - Replace each line containing a specific word from the first file with the line from the second file 如何用python列表中的相应元素替换文件中每行的第一个单词? - How to replace first word of each line in a file with the corresponding element from a list in python? 如何更改文本文件每一行的第一个字符? - How to change first character in each line of a text file? 如何替换文本文件中每行空格前的第一个数字 - How to replace first number before a space in each line in a text file 如何检查文本文件中每一行末尾的特定字符 - How do check for a specific character at the end of each line in a text file 如何替换python中“.txt”文件每一行的第一个数字? - How to replace first number from each line of a ".txt" file in python? 将文本文件每一行中的每个字符添加到Python列表中 - Add each character from each line of a text file, to a list in Python 如何删除每行中每个单词的前 3 个字符 - how to remove first 3 character of every word in each line 在文本文件的每一行上保留最后一个字,删除其余部分 - Keep last word on each line of text file, delete rest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM