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

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

Python:如何讀取段落的每一行并復制具有特定單詞的行

Python:如何讀取段落的每一行并復制具有特定單詞的行

躍然一笑 2023-12-29 15:32:44
我需要閱讀一個段落,我需要復制只有關鍵字的行。段落是這樣的:aaaaaaaaaaa[new,aaa] < name of the file with path ] //asabbsjkorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap[mod] <name of the file with path 我的算法:if keyword exists in the line :      copy that line else:       leave it
查看完整描述

2 回答

?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

嘗試這幾行代碼:


copy_lines= []

for line in paragraph.split('\n'):

    if keyword in line:

        copy_lines.append(line)

print(copy_lines)

或一張內襯:


copy_lines= [line for line in paragraph.split('\n') if keyword in line]


查看完整回答
反對 回復 2023-12-29
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

如果您嘗試從文件中讀取該段落:


keyword = "your_keyword"


with open("demofile.txt", "r") as f:

    line_list = f.readlines()

    magic_lines = [line for line in line_list if keyword in line]


查看完整回答
反對 回復 2023-12-29
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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