小编Try*_*ard的帖子

Python文本文件搜索

我有一个大文本文件,我需要从中提取几个值.文本文件有很多我不需要的信息.有没有办法我可以搜索一行中的特定术语并返回该行中的第一个值.请举例如下

text
text text
text
text text text
text text

aaaaa     text      sum

text
text
text
Run Code Online (Sandbox Code Playgroud)

我需要搜索sum并返回值 aaaaa

有没有办法可以做到这一点?

python text

0
推荐指数
1
解决办法
334
查看次数

Python ==许多语句而不是if/elif

我在下面尝试这个.

my_list = []

for row in reader: 
    a = row[0]
    b = row[1]
    c = row[2]
    s=("{0:<5s} {1:<5s} {2:<8s} ".format(a,b,c))
    lst = my_list.append(s)
    if b == ("Home"):
        n_lst = new_lst.appen(s)
Run Code Online (Sandbox Code Playgroud)

我想如果输出中的行b等于"home""消失"等,则将该行放入新列表中.我试过了

if b == ("home", "gone"):
Run Code Online (Sandbox Code Playgroud)

但这不起作用,有没有办法继续添加到我的if ==语句而不是做一堆elif语句?

python

0
推荐指数
1
解决办法
160
查看次数

Python列表删除追加

我有一个文件放入列表中,我想从中获取一些东西,并附加到另一个列表(我没有问题),我遇到的问题是删除第一个列表中的东西.下面是我尝试过但它只从原始列表中删除所有其他内容.

list:
bob     g1  3110
bob     g2  244
bob     g3  -433
greg    fun112  10595
greg    fun113  -1203
greg    fun114  -3049.999
greg    fun115  3808
greg    fun116  320
greg    got112  -600
greg    got113  5958
greg    got114  1249


file1 = open('test','rb').read().splitlines()
file1=sorted(file1)
test_group = ['fun','got']
test= []

for product in file1:
    spt = product.split(",")
    for line in spt:
        if line[:3] in test_group:
            x = test.append(product)
            y = file1.remove(product)
Run Code Online (Sandbox Code Playgroud)

test []列表很好,我想要的所有项目都没有问题,但是当我查看file1时,它只会取出所有其他的'fun'和'got'行

为什么这只是取出其他每一个,我该如何解决?

python python-2.7

0
推荐指数
1
解决办法
2万
查看次数

Python __main __.__ file__

我有一个简单的问题,我在python文档中找到答案时遇到问题.

文件名= Test_.py

import __main__

def test():
    print('test text')

if __name__ == "__main__":
    print(__main__.__file__)
    test()
Run Code Online (Sandbox Code Playgroud)

当我从cmd行运行它时,它返回:

c:\Python27\Test_.py
'test text'
Run Code Online (Sandbox Code Playgroud)

但如果我通过单击"运行"(F5)从python运行它,我得到.

Traceback (most recent call last):
  File "C:\Python27\Test_.py", line 7, in <module>
    print(__main__.__file__)
AttributeError: 'module' object has no attribute '__file__'
Run Code Online (Sandbox Code Playgroud)

为什么我可以从命令行运行它,它工作正常,但如果我从python运行它我得到一个错误.c:\Python27\Test_.py当我从python运行它时,有没有办法获得.

python

0
推荐指数
1
解决办法
3385
查看次数

标签 统计

python ×4

python-2.7 ×1

text ×1