【问题标题】:Python: Find and Print strings, multiple instances per linePython:查找和打印字符串,每行多个实例
【发布时间】:2020-05-08 20:03:49
【问题描述】:

我找不到我的确切问题的答案,也无法与之相关。 这是我所拥有的:

file = input('put file name here: ')

try:
        fhand = open(file)

        for line in fhand:
                line = line.rstrip()
                if line.find('[') == -1: continue
                atpos1 = line.find('[')
                atpos2 = line.find(']')
                info = line[atpos1+1:atpos2]

                print(info)
except:
        print('incorrect file name')

print('you are done')
quit()

这对于括号之间的字符串的第一个实例非常有效,但有时每行有多个实例。如何打印文档中括号内的每一个单词/字符串?

【问题讨论】:

  • 尝试给它取一个不存在的名称。确保崩溃。
  • 我解决了这个问题。我的问题在代码下方。

标签: python-3.x recursion data-analysis


【解决方案1】:

你可以继续寻找括号,直到没有括号是这样的:

for line in fhand:
    line = line.rstrip()
    while line.find('[') != -1:
        atpos1 = line.find('[')
        atpos2 = line.find(']')
        info = line[atpos1+1:atpos2]
        line = line[atpos2:len(line)]
        print(info)

【讨论】:

  • 会起作用 - 但你为什么要切线?这会创建一个新的一次性字符串....只需使用带有第二个参数的 find 开始搜索就更干净了。看上面。您还偶尔为每个 [ 的位置搜索两次,然后获取切片的位置
【解决方案2】:

您使用 str.find(sub[, start[, end]]) 并在最后一次找到 ']' 之后使用 start 值进行新搜索 - 将其放入 while 循环,直到找不到更多 '['

file = "t.txt"

with open(file,"w") as f:
    f.write("""nothing
some [one] some
some [one] some [two] more [three] things
some [one] some""")


try:
    with open(file) as f:
        for idx, line in enumerate(f,1):
            line = line.rstrip()
            pos = line.find('[')           # store first position
            while pos != -1:               # only continue if found
                atpos2 = line.find(']', pos)   # find end after pos
                info = line[pos+1:atpos2]      # get part

                pos = line.find('[',atpos2)    # find next start after end
                print(f"Found '{info}' in line {idx}") 
except Exception as e:  # maybe print the error as well...
        print('stop being a stupid', e)


print('you are done')

输出:

Found 'one' in line 2
Found 'one' in line 3
Found 'two' in line 3
Found 'three' in line 3
Found 'one' in line 4
you are done

atpos2 = line.find(']', pos) # find end after pos 部分对于像这样的字符串很重要

'this ] will give you [weird] outputs [ elsewise'

【讨论】:

  • 谢谢!比我的技能水平高一点,但这很好。我正在努力学习,这对我有很大帮助!
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
相关资源
最近更新 更多