0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python ファイルの指定の文字を含む行番号を取得

Last updated at Posted at 2021-05-15

txtファイルを読み込んで「梅雨」という単語を含む行番号と数値を含む行番号を取得する

from tkinter import filedialog
import re

dir = "D:\Python\Hello" #ダイアログの初期フォルダ
typ = [("", '*.txt')]
file_path = filedialog.askopenfilename(
    title="文字抽出ファイル名を指定", filetypes=typ, initialdir=dir) 

f = open(file_path, 'r', encoding='UTF-8')
lines = f.readlines()
lines_strip = [line.rstrip() for line in lines] #改行文字を除く
line_num = [i for i,moji in enumerate(lines_strip) if '梅雨' in moji] #「梅雨」を含む行番号を取得
print(line_num) 

for i,moji in enumerate(lines_strip):
    result = re.sub(r"\D", "", lines_strip[i]) #数値を含む行番号を出力
    print(result)
f.close()

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?