如何使用str.replace从spinbox中获取值,然后在文本文件中替换该值的实例?

时间:2021-08-08 06:01:16

I am using the re module of python to find all instances of 2 patterns in a text file. I have a spinbox which returns the value of that which has been selected.

我正在使用python的re模块在文本文件中查找2个模式的所有实例。我有一个旋转框,它返回已选择的值。

from tkinter import *
import re

root = Tk()

num_names = open('numerical_sat_names.txt', 'r')
num_file = num_names.read()

satellite_TLE = open('TLE.txt', 'r')
TLE_file = satellite_TLE.read()
text = TLE_file

choice_var = tk.StringVar()    

class FindTLE(tk.Frame):
    pattern1 = r'(^.) (.....)(.) (........) (..)(............) (..........) (........) (........) (.) (....)(.$)'
    pattern2 = r'(^.) (.....) (........) (........) (.......) (........) (........) (...........)(.....)(.$)' 

    multiline1 = re.compile(pattern1, re.MULTILINE)
    multiline2 = re.compile(pattern2, re.MULTILINE)
    print ('Multiline   :')
    for match in multiline1.findall(text):
        print (' %r' % (match,))
    if not pattern1:
        raise TypeError('Bad line1 %s' % multiline1)
    print ('Multiline2   :')
    for match in multiline2.findall(text):
        print (' %r' % (match,))
    if not pattern2:
        raise TypeError('Bad line2 %s' % multiline2)

def TLE_selected():
    selected = str(choice_var.get())
    print('selected   :', selected)
    str.replace('.....U', selected[1])


TLE_spinbox=tk.Spinbox(textvariable=choice_var, values=num_file,
                    command=TLE_selected)
TLE_spinbox.pack()

root.mainloop()

I would like the value of the spinbox to replace something within the text file; 'TLE.txt'; that is, (.....U). However I get the typeError:

我希望spinbox的值能够替换文本文件中的内容; 'TLE.txt';也就是说,(..... U)。但是我得到了typeError:

    str.replace('.....U', selected[1])
TypeError: replace() takes at least 2 arguments (1 given)

The ('.....U') should correspond with part of 'pattern1' and follow the same structure as that which has been selected.

('..... U')应与'pattern1'的一部分对应,并遵循与已选择的结构相同的结构。

I am quite new to python and therefore would appreciate some guidance as to what I am doing wrong, and how to go about solving this problem.

我是python的新手,因此会对我做错了什么以及如何解决这个问题有一些指导。

1 个解决方案

#1


0  

replace can be used in two methods "Hello".replace("H", "h") which needs two arguments or str.replace("Hello", "H', "h") which needs 3 arguments - and here is your problem.

replace可以用于两个方法“Hello”.replace(“H”,“h”),它需要两个参数或者str.replace(“Hello”,“H”,“h”)需要3个参数 - 这里是你的问题。

(Comment by furas)

(furas评论)

#1


0  

replace can be used in two methods "Hello".replace("H", "h") which needs two arguments or str.replace("Hello", "H', "h") which needs 3 arguments - and here is your problem.

replace可以用于两个方法“Hello”.replace(“H”,“h”),它需要两个参数或者str.replace(“Hello”,“H”,“h”)需要3个参数 - 这里是你的问题。

(Comment by furas)

(furas评论)