如何在给定的行中找到python中两个字符之间的文本



我正在尝试编写一个多剪贴板程序,并且正在努力寻找一种方法来检索给定行中两个给定字符之间的文本。我的代码将用户的剪贴板存储到一个给定关键字下的txt文件中,用|分隔。我希望能够使用加载命令检索此文本,而不需要关键字或下一行。目前,我可以在文件中找到关键字,但找不到检索文本的方法。我该怎么做?

这是我的代码供参考:

import sys
import pyperclip
import json

command = sys.argv[1:2]
if command == ['save']:
with open ('clipboard.txt', 'a') as file:
storeas = input('Store clip as: ')
file.write(f"{storeas} | {pyperclip.paste()}n")
file.close()
if command == ['load']:
with open ('clipboard.txt', 'r') as file:
if ("".join(sys.argv[2:]) in file.read()):
print('found')
else:
print('not found')
print(sys.argv[2:])

如果您假设;键";你使用的不包含|字符,那么你可以很容易地为你读取的每一行使用

delimiter_position = line.find("|")

要查找,行中的分隔符在哪里。要访问存储的数据,请使用

line[delimiter_position:]

或类似的。

例如

>>> a = "foo | bar asdf"
>>> delimiter_position = a.find("|")
>>> a[delimiter_position:]
'| bar asdf'
>>> a[delimiter_position + 1:]
' bar asdf'

如果你读了一个文件,你可以使用

with open(filename) as f:
for line in f:
...

在行上迭代。

如果有人在键或值中使用|,整个机制就会崩溃。使用其他东西而不是文本文件可能是个好主意,例如sqlite。

import sys
import pyperclip
import json

command = sys.argv[1:2]
if command == ['save']:
with open ('clipboard.txt', 'a') as file:
storeas = input('Store clip as: ')
file.write(f"{storeas} | {pyperclip.paste()}n")
file.close()
if command == ['load']:
with open ('clipboard.txt', 'r') as file:
storeas = "".join(sys.argv[2:])
i = 0
for line in file.read().split('n'):
if line.startswith(storeas):
print(''.join(line.split('|')[1:]))
i+=1
if not i:
print('not found')
print(sys.argv[2:])

最新更新