Home > database >  How to find the text between two characters in python in a given line?
How to find the text between two characters in python in a given line?

Time:08-01

I am trying to write a multi-clipboard program and am struggling with finding a way to retrieve text between two given characters in a given line. My code stores the user's clipboard to a txt file under a given key word, separated by |. I want to be able to retrieve this text with a load command, without the key word or the next line. Currently, I can find if the key word is found in the file but cannot find a way to retrieve the text. How do I do that?

Here is my code for reference:

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:])

CodePudding user response:

If you assume, that the "keys" you use does not contain a | character, then you can easily for each line you read use

delimiter_position = line.find("|")

to find, where in the line the delimiter is. To then access the stored data, use

line[delimiter_position:]

or similar.

For example

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

If you read a file, you can use

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

to iterate over the lines.

This whole mechanism breaks, if someone uses a | in the key or in the values. It might be a good idea to use something else instead of a text file -- for example sqlite.

CodePudding user response:

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:])
  • Related