我想在Python中尝试一些实用且具体的东西,并且我在玩口袋妖怪时意识到浪费时间插入代码。有一个代码的文本文件,代码看起来像这样:
位于最顶端(82003884)
0001 = Master Ball
...
82003884代码是基本代码,并且XXXX代码(masterball = 0001)被添加到最后以获得该特定项目。
我想修改文本文件中的所有代码,以便将第一个和第二个代码连接在一起。问题是,我还不知道如何处理它。我的第一反应是用一个以主代码开头的新单词搜索并替换所有4个字符的“单词”。但我真的不明白Python如何解释像“0001 = Master Ball”这样的行以及如何将较长的主代码与4字符(XXXX)代码连接起来。
此外,我不知道基于4个字符的标准的find-replace是否足够有选择性地将进程限制为代码本身(并且不会影响奇怪的4个字符的描述词,如“nest”)等)。
这是它的样子:
0001 = Master Ball
0002 = Ultra Ball
0003 = Great Ball
0004 = Poke Ball
0005 = Safari Ball
0006 = Net Ball
...
答案 0 :(得分:0)
您描述它的方式是只有一个基本代码。在这种情况下,您可以读取文件的第一行,并将此行的内容放在每隔一行的前面。
如果有多个基本代码(似乎更有可能),你必须决定你作为一个人如何决定某些东西是否是基本代码。有白线吗?基本代码总是一个包含8位数的字符串吗?一旦你知道了,就把它翻译成Python或任何其他语言理解的规则。
修改
由于只有一个基本代码,因此以下脚本已经存在。
<强> pokemon.txt 强>
12345678
0001 = Master Ball
0002 = Ultra Ball
0003 = Great Ball
0004 = Poke Ball
0005 = Safari Ball
0006 = Net Ball
<强> prepend.py 强>
def prepend_header(file_in, file_out):
with (open(file_in, 'r')) as f:
base_code = f.readline()[:-1] # -1 to strip newline character
new_string = ''
for line in f:
new_string += base_code + line
print (new_string)
with (open(file_out, 'w')) as f:
f.write(new_string)
if __name__ == '__main__':
prepend_header('pokemon.txt', 'pokemon_new.txt')
<强> pokemon_new.txt 强>
123456780001 = Master Ball
123456780002 = Ultra Ball
123456780003 = Great Ball
123456780004 = Poke Ball
123456780005 = Safari Ball
123456780006 = Net Ball
答案 1 :(得分:0)
你想要的是正则表达式或正则表达式:正则表达式。他们的速度通配符是通配符。在这里,您希望一个匹配主代码,即^\d{8}$
或^\(\d{8}\)$
,具体取决于这些括号是否在文件中。然后将其保存在变量中,并在将所有行再次保存到文件之前将其添加到每个后续行。
Python 3.4中的示例,假设文件名为&#34; pokemon_codes.txt&#34;并且在当前目录中等等:
import re # for regular expressions
import os # for renaming/deleting files
# open the file line by line, updating into temp file then overwriting
with open('pokemon_codes.txt', mode='r') as f_codes:
with open('pokemon_codes.out', mode='w') as f_out:
for line in f_codes:
if re.match('^\d{8}$', line):
master = line.rstrip() # now we know what the current master code is
else:
f_out.write(master + line) # update with the master code/current code combination followed by the description, if any
os.remove('pokemon_codes.txt')
os.rename('pokemon_codes.out', 'pokemon_codes.txt')