我有2个文件:仅由1行(字符串)组成的fileA和由2行组成的文件B:第1行代表“主题”序列,第2行代表“查询”。
fileA(just 1 row):
*****s**e**********************************************q*
fileB(2 rows):
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
我需要产生一个文件C,如果在文件A中有一个“ s”,他将把相应的索引位置的主题字符放入。如果有q,则他放置查询字符。如果有“ e”,则他放置查询字符。如果有*,他会输入主题字符。
Output:
AAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA
我的代码:
ff = open("filea.txt")
gg = open("fileb.txt")
file_as_list = ff.readline()
file_as_last = gg.readlines()
query = file_as_last[0]
subject = file_as_last[1]
for i in file_as_list:
z = -1
while z <= len(file_as_list):
if i == "*":
f = open('output.txt', 'a+', encoding='utf-8')
f.write(subject[z])
z += 1
elif i == "s":
f = open('output.txt', 'a+', encoding='utf-8')
f.write(subject[z])
z += 1
elif i == "e":
f = open('output.txt', 'a+', encoding='utf-8')
f.write(query[z])
z += 1
elif i == "q":
f = open('output.txt', 'a+', encoding='utf-8')
f.write(query[z])
z += 1
break
事物或多或少地起作用,但不能正常工作:我一直认为循环仅适用于第一条语句,并且产生的输出只是主题的副本
with open
,因此所有文件将自动关闭string
转换为list
,并且.strip
用于删除\n
和\r
lists
加载到pandas.DataFrame
中>pandas.DataFrame.apply
与axis=1
进行逐行运算np.where
返回正确的值out
写入list
,然后将其隐藏为str
out
写入output.txt
文件import pandas as pd
import numpy as np
with open('fileA.txt', 'r') as filA:
with open('fileB.txt', 'r') as filB:
with open('output.txt', 'w', newline='\n') as output:
fil_a = filA.readline()
fil_b = filB.readlines()
sub = [x for x in fil_b[0].strip()]
que = [x for x in fil_b[1].strip()]
line = [x for x in fil_a.strip()]
df = pd.DataFrame({'A': line, 'sub': sub, 'que': que})
df['out'] = df.apply(lambda x: str(np.where(x[0] in ['*', 's'], x[1], x[2])), axis=1)
out = df.out.to_list()
out = ''.join(x for x in out)
output.write(out)