TQC考題:
範例輸入/輸出:
read.txt內容:
hello world!
what is the weather like out there?
are you ok?
what’s today’s date?
excuse me!
happy new year
are you tired?
what is your name?
it’s a nice day!
make persistent efforts
you can make it!
使用pandas套件:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 08:02:37 2023
@author: SavingKing
"""
import os
import pandas as pd
n = eval( input("請輸入您想要轉換的列數:\t") )
df = pd.read_csv("read.txt",header=None)
ser = df.squeeze()
ser_title = ser.str.title()
ser_title_slice = ser_title[0:n]
print("ser_title_slice:\n",ser_title_slice)
ser_title_slice.to_csv("write.txt",index=False,header=False)
輸出結果:
TQC在這裡考一個陷阱
.title() 會把today‘s轉為Today‘S
要用.replace() 修正
本篇code皆缺少這一步驟
不使用套件
code:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 08:02:37 2023
@author: SavingKing
"""
import os
n = eval( input("請輸入您想要轉換的列數:\t") )
with open("read.txt", 'r') as f:
lis = f.readlines()
print( "readlines():\n",lis )
#cnt=1
with open("write.txt", 'w') as f:
for idx,ele in enumerate(lis,1):
if idx <= n:
line = ele.title()
f.write(line)
#idx+=1 #不需要,idx本來就會隨著enumerate+1
else: break
dirname = os.path.dirname(__file__)
ex_path = os.path.join(dirname,"write.txt")
print("檔案已經輸出到:\n",ex_path)
輸出結果:
不使用套件
code:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 08:02:37 2023
@author: SavingKing
"""
n = eval( input("請輸入您想要轉換的列數:\t") )
f = open("read.txt", 'r')
w = open("write.txt", 'w')
count=1
for i in f:
if count <= n:
print(f"{i.title()}", end="")
w.write(i.title())
count += 1
else:
break
w.close()
f.close()
輸出結果:
推薦hahow線上學習python: https://igrape.net/30afN
TQC在這裡考一個陷阱
.title() 會把today‘s轉為Today‘S
要用.replace() 修正
code:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 08:02:37 2023
@author: SavingKing
"""
import os
import pandas as pd
n = eval( input("請輸入您想要轉換的列數:\t") )
df = pd.read_csv("read.txt",header=None)
ser = df.squeeze()
# ser_title = ser.str.title().replace(r"\b'S\b", "'s", regex=True)
##使用正則表示法也可
ser_title = ser.str.title()
ser_title = ser_title.str.replace("'S", "'s")
ser_title_slice = ser_title[0:n]
print("ser_title_slice:\n",ser_title_slice)
ser_title_slice.to_csv("write.txt",index=False,header=False)
ser_title = ser.str.title().replace("'S", "'s")
會失敗
需要分段做或
使用正則表示法
輸出結果:
推薦hahow線上學習python: https://igrape.net/30afN