【问题标题】:Save certain strings from a text file in Python在 Python 中保存文本文件中的某些字符串
【发布时间】:2018-02-08 08:04:06
【问题描述】:

我需要从文本文件中保存某些字符串。我有一个需要保存的关键字列表,每个关键字都在一行上。 一个例子是:

name=hydrogen
symbol=h
number=1

我需要保存字符串 Hydro、h 和 1,但我尝试使用单个字符,但不知道该怎么做。你能帮忙吗?

import urllib2
import re

nome = ["hydrogen","helium","lithium","berilium"]
f = open('tavolaperiodica.txt','w')
for x in range(0, 3):
    data = urllib2.urlopen("https://en.wikipedia.org/w/index.php?action=raw&title=Template:Infobox%20" + nome[x])
    #data = data.split("\n") # then split it into lines


    for line in data:
        #print line
        f.write(line)

    f.write("\n\n\nNew\n\n\n")


f.close()

infile = "tavolaperiodica.txt"
outfile = "cleaned_file.txt"

delete_list = ["|", "}", "{"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    for word in delete_list:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()

lines = []
pat = re.compile(r"\binorganic\b")
with open('cleaned_file.txt') as fp:
    line = fp.readline()
    cnt = 1
    while line:
        #print("Line {}: {}".format(cnt, line.strip()))
        line = fp.readline()
        lines.append(line.strip())
        if pat.search(line) != None:
            print("Found it.")

        cnt += 1

paramethers = ["name","symbol","number"]
index = 0
par = list("")
value =  list("")
pr = open('prova.txt', 'w')
for i in range(0, 3):
    print("linea: ", i)
    print(len(lines[i]))
    x = 0
    while x < len(lines[i]):
        print(x)

        if lines[i][x] == "=":
            index = x
            print("Uguale", index)
            y = 0
            for y in range(index+1, len(lines[i])):
                print("y ", y)
                #value.append(lines[i][y])
                z = 0
                while z > y:
                    print("cisono")
                    par.append(lines[i][z])
                    for d in range(0, len(paramethers)):
                        if par == paramethers:
                               value.append(lines[i][y])
                    d+=1
                z+=1
            y+=1
        else:
            print("eskere")

        x = x + 1
    value.append("\n\n")
i+=1
print(value)
pr.write(''.join(value))

【问题讨论】:

  • 您或许应该在问题中添加您尝试过的代码?
  • 刚刚用代码更新了帖子

标签: python string python-2.7 text char


【解决方案1】:

以下是解决此问题的简单方法。它可能是理想的,也可能不是理想的,这取决于您真正需要什么:

values = []
with open('foo.txt', 'rt') as f:
    for line in f:
        try:
            values.append(
                line.split('=', 1)[1].strip())
        except IndexError:
            # depending on your needs; if you want to ignore lines
            # that are not key=value, replace the append with a
            # pass
            values.append('')
for v in values:
    print "got:", v

其中 foo.txt 是您的文本文件。这将遍历每一行,在第一个 `=.

'a=b=c'.split('=', 1) 获取您['a', 'b=c']

对于不包含 = 或之后没有任何内容的行,strip('=', 1) 将返回一个只有一个元素的列表,因此尝试获取索引为 1 的元素将抛出 IndexError您可以根据需要处理。

最后,strip() 去掉了右侧字符串开头和结尾的空格,以防您有像 a = b 这样的字符串。

【讨论】:

  • 它给了我这个错误: print line.split('=', 1)[1].strip() IndexError: list index out of range
  • 我用 line.split('=', 1)[0].strip() 改变了 line.split('=', 1)[1].strip() ,它似乎工作.在输出中,虽然它只给了我短语的开头,直到 "="
  • 你的行可能只有key=(没有价值)。我会编辑答案来解决这个问题。
  • 不用担心。如果您打算更多地使用 python,请查看它的许多功能。您可能会找到解决许多问题的简单快捷的方法。一旦你掌握了它的窍门,你就会发现它是为了让你的生活变得轻松而编写的 :)
猜你喜欢
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 2018-05-16
相关资源
最近更新 更多