解决了这段代码中的一些问题,由于某种原因,我的方法验证检查不太有效。我想要它做的就是验证用户的输入仅包含字母 G、C、A、T,然后再转到 at_calculate 方法,该方法对输入序列执行数学运算。任何帮助/提示将不胜感激。
import re
from tkinter import *
class AT_content_calculator:
def __init__(self, master):
#initialising various widgets
frame_1 = Frame(master)
frame_1.pack()
self.varoutput_1 = StringVar()
self.label_1 = Label(frame_1, text="Please enter a DNA sequence:")
self.label_1.pack()
self.entry_1 = Entry(frame_1, textvariable=self.dna_sequence)
self.entry_1.pack()
self.output_1 = Label(frame_1, textvariable=self.varoutput_1)
self.output_1.pack()
self.button_1 = Button(frame_1, text="Calculate", command=self.validation_check)
self.button_1.pack()
def dna_sequence(self):
self.dna_sequence = ()
def validation_check(self):
#used to validate that self.dna_sequence only contains letters G, C, A, T
if re.match(r"GCAT", self.dna_sequence):
self.at_calculate()
else:
self.varoutput_1.append = "Invalid DNA sequence. Please enter again."
self.validation_check()
def at_calculate(self):
#used to calculate AT content of string stored in self.dna_sequence
self.dna_sequence = self.entry_1.get()
self.total_bases = len(self.dna_sequence)
self.a_bases = self.dna_sequence.count("A")
self.b_bases = self.dna_sequence.count("T")
self.at_content = "%.2f" % ((self.a_bases + self.b_bases) / self.total_bases)
self.varoutput_1.set("AT content percentage: " + self.at_content)
root = Tk()
root.title("AT content calculator")
root.geometry("320x320")
b = AT_content_calculator(root)
root.mainloop()
请您参考如下方法:
如果你想验证用户的输入只包含字母 G、C、A、T,你需要将这些字符放在一个字符类中,该字符类将匹配这些字符的任意组合:
注意 :self.dna_sequence 是一个函数,你不能将它传递给 match 函数,尽管它不正确。你需要返回该函数中的输入值:
def dna_sequence(self):
dna_sequence = self.entry_1.get()
return dna_sequence
然后做:
if re.match(r"[GCAT]+", self.dna_sequence()):
[GCAT]+ 将匹配长度为 1 或更大的字符的任何组合。如果您希望它的长度为 4,您可以使用 [GCAT]+{4}。
但这也会匹配重复的字符。像 GGCC。如果你不想要这样的东西,你可以使用 set.intersection :
if len(self.dna_sequence())==4 and len(set(GCAT).intersection(self.dna_sequence()))==4:
#do stuff
或者更好的方法:
if sorted(self.dna_sequence)==ACGT:
#do stuff
