亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在列表中查找字符索引

在列表中查找字符索引

陪伴而非守候 2023-08-15 17:10:24
我想在 .txt 文件中搜索某個字符 (X),如果存在,則執行某個操作。不幸的是這段代碼不起作用:file = "test.txt"file = open(file, "r") lines = file.readlines()# char in the listif "X" in lines:    print('X is present in the list')# char not in the listif "X" not in lines:    print('X is not present in the list')測試.txt 文件:XX X XXX X XXXXXXX XX X    XX有什么想法嗎?PS:即使將“X”更改為“X”也不起作用。
查看完整描述

3 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

如果您需要知道X出現的行號:


target = 'X'

counter = 0

with open('testing.txt') as f:

    for i, line in enumerate(f):

        if target in line:

            counter += 1

            print('target is present in line {}'.format(

                i+1))


print('target appears in {} lines'.format(counter))

如果您還需要知道X出現的列號:


target = 'X'

counter = 0

with open('testing.txt') as f:

    for i, line in enumerate(f):

        for j, char in enumerate(line):

            if target == char:

                counter += 1

                print('target is present in line {} at column {}'.format(

                    i+1, j+1))


print('target appears {} times'.format(counter))

一些澄清:

  • with ... open完成后自動關閉文件,因此您無需記住顯式關閉它

  • for i, line in enumerate(f):逐行迭代,而不將它們一次性全部加載到內存中。


查看完整回答
反對 回復 2023-08-15
?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

由于readlines()是一個列表,您需要迭代并簽入行。也許您可以用于for else此目的:


file = "testing.txt"

file = open(file, "r") 

lines = file.readlines()


# char in the list

for line in lines:

    if "X" in line:

        print('X is present in the list')

        break

else:

    print('X is not present in the list')

它迭代每一行,如果任何行有字符,則break僅else在任何行中都找不到字符時才運行。


更新

如果你想計數,那么你可以簡單地在循環中增加計數器,一旦循環完成檢查計數器:


file = "testing.txt"

file = open(file, "r") 

lines = file.readlines()


# char in the list

counter = 0

for line in lines:

    if "X" in line:

        counter += 1  # < -- count

        

if counter: # check    

    print('X is present in the list')

        

else:

    print('X is not present in the list') 


查看完整回答
反對 回復 2023-08-15
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

正如您所要求的,我將輸出一個包含 item 的列表Yes, there are 3 X's。


我有我的dataf.txt文件:


XXX X XX X XX

X ASD X F FFFF XX

D X XXX X EFX

A F G

將數據讀入文件并計算 X 的數量(注意:我使用了列表理解 hack!)


with open('dataf.txt','r') as fl:

    data = fl.readlines()

    a = ['Yes, there are '+str(i.count('X')) + " X's" if 'X' in i else "No X's" for i in data]

    print(a)

輸出:


["Yes, there are 9 X's", "Yes, there are 4 X's", "Yes, there are 6 X's", "No X's"]


查看完整回答
反對 回復 2023-08-15
  • 3 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號