def find_1st(file,x):
infile=open(file,"r")
outfile=open("result.txt",'w')
date=infile.read()
position=date.find(x)
if position==-1:
print(x+"没有被找到\n")
else:
print(x+'在',str(position)+'被第一次找到\n')
infile.close()
outfile.close()
print('done')
print(find_1st('/Users/wangzhehan/Downloads/article.txt','computer'))
改成相对路径:
def find_1st(file,x):
infile=open(file,"r")
outfile=open("result.txt",'w')
date=infile.read()
position=date.find(x)
if position==-1:
print(x+"没有被找到\n")
else:
print(x+'在',str(position)+'被第一次找到\n')
infile.close()
outfile.close()
print('done')
find_1st('article.txt','computer')
用相对路径
不知道你这个问题是否已经解决, 如果还没有解决的话:后续操作同上。
解决方案:
在Python中查找并修改给定字符串中的环线部分可以采用正则表达式的方式进行操作,具体步骤如下:
import re
pattern = r"环线\d+"
s = "某地区公交车经过环线1,需在该站下车。"
result = re.search(pattern, s)
new_str = re.sub(pattern, "线路{}".format(result.group().lstrip("环线")), s)
print(new_str)
完整代码如下:
import re
s = "某地区公交车经过环线1,需在该站下车。"
pattern = r"环线\d+"
result = re.search(pattern, s)
if result is not None:
new_str = re.sub(pattern, "线路{}".format(result.group().lstrip("环线")), s)
print(new_str)
else:
print("未找到环线部分")
操作提示:
以上代码中,使用re.search()可以用于在一个字符串中搜索正则表达式所匹配的内容,并返回一个包含匹配结果信息的match对象;而re.sub(pattern, repl, string)可以用于在一个字符串中搜索正则表达式所匹配的内容,并将其替换为指定的字符串。在使用正则表达式时,常常需要用到一些特殊字符来表示匹配模式,例如,点号(.)用于匹配任何字符,星号(*)用于匹配零个或多个字符,加号(+)用于匹配一个或多个字符,问号(?)用于匹配零个或一个字符等等。
参考资料: