Category Archives: python

Pythonでランダムな文字列を作成するサンプル

コード下記

import os, math
from base64 import b64encode
randStr = lambda n: b64encode(os.urandom(int(math.ceil(0.75*n))),’-_’)[:n]

for x in xrange(5):
print randStr(10)

Pythonでテキストファイルを読む方法まとめ

1.readline()
file = open(“startnews24python.txt”)
while 1:
line = file.readline()
if not line:
break
pass # do something
file.close()
2.fileinput
import fileinput
for line in fileinput.input(“startnews24python.txt”):
pass

3.readlines()
file = open(“startnews24python.txt”)
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
file.close()

4.イテレータ
file = open(“startnews24python.txt”)
for line in file:
pass # do something
file.close()

Python入門–Datetime、TimeStamp、UTC、localtimeの相互変換する方法

1.TimeStampをDatetimeに変換する
def timestamp2datetime(timestamp, convert_to_local=False):
”’ Converts UNIX timestamp to a datetime object. ”’
if isinstance(timestamp, (int, long, float)):
dt = datetime.datetime.utcfromtimestamp(timestamp)
if convert_to_local:
dt = dt + datetime.timedelta(hours=8)
return dt
return timestamp

2.DatetimeをTimeStampに変換する
def datetime2timestamp(dt, convert_to_utc=False):
”’ Converts a datetime object to UNIX timestamp in milliseconds. ”’
if isinstance(dt, datetime.datetime):
if convert_to_utc:
dt = dt + datetime.timedelta(hours=-8)
timestamp = total_seconds(dt – EPOCH)
return long(timestamp)
return dt
3.UTC時間のTimeStamp
def timestamp_utc_now():
return datetime2timestamp(datetime.datetime.utcnow())

4.local時間のTimeStamp
def timestamp_now():
return datetime2timestamp(datetime.datetime.now())

5.UTC時間をローカル時間に変換する
# python-dateutilのインストール
# Ubuntu下:sudo apt-get install python-dateutil
#PIP:sudo pip install python-dateutil
from dateutil import tz
from dateutil.tz import tzlocal
from datetime import datetime

# get local time zone name
print datetime.now(tzlocal()).tzname()

# UTC Zone
from_zone = tz.gettz(‘UTC’)
# China Zone
to_zone = tz.gettz(‘CST’)

utc = datetime.utcnow()

# Tell the datetime object that it’s in UTC time zone
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
local = utc.astimezone(to_zone)
print datetime.strftime(local, “%Y-%m-%d %H:%M:%S”)

Python入門–プログラム実行時間を計測する方法

コード下記
import time
def start_sleep():
time.sleep(3)
if __name__ == ‘__main__’:
#The start time
start = time.clock()
#A program which will run for 3 seconds
start_sleep()
#The End time
end = time.clock()
print(“The function run time is : %.03f seconds” %(end-start))
# End

Python入門–日付(datetime)の基本的な使い方

コード下記:

import datetime, calendar

lastFriday = datetime.date.today( )
oneday = datetime.timedelta(days=1)
lastFriday -= oneday
while lastFriday.weekday( ) != calendar.FRIDAY:
lastFriday -= oneday
print lastFriday.strftime(‘%A, %d-%b-%Y’)

Pythonで昨日の日付の計算を実現するコード

コード下記
#-*-coding:utf-8-*-
import datetime
def getYesterday(): #
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday

「Python入門」for、while繰返し処理の使い方

#繰返し処理1
names = [‘Michael’, ‘Bob’, ‘Tracy’]
for name in names:
print name

# 繰返し処理2
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print x

#繰返し処理3
for x in range(101):
print x

# while
n = 88
while n > 0:
print n
n = n – 2

CentOS7にPython2.7.4、pip環境を作る方法

1.pythonのインスントール
#!/bin/bash
#ソースパッケージのインスントール
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9

#コンパイルのインスントール
./configure
make
make install
2.pipのインスントール
#!/bin/bash
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
3.startnews24_test.py
サンプルコード:
#!/usr/bin/env python
# -*- coding:utf8-*-

print ‘welcome to startnews24’
print(‘welcome to startnews24’)

print ‘startnews24′,’com’
name = raw_input()

実行
python startnews24_test.py

「python学習」pythonでファイルを読み取って、mysqlでデータを挿入する方法

Javaコード:
import os
import mysql.connector

config = {
‘user’: ‘root’,
‘password’: ‘******’,
‘host’: ‘127.0.0.1’,
‘database’: ‘startnews24_com_db’,
‘raise_on_warnings’: True,
}
cnx = mysql.connector.connect(**config)

class ReadFile:
def readLines(self):
f = open(“E:/data_startnews24/2015-3-13.txt”, “r”, 1, “utf-8”)
i=0
list=[]
for line in f:
strs = line.split(“\t”)
if len(strs) != 5:
continue
data=(strs[0], strs[1], strs[2], strs[3], strs[4].replace(“\n”,””))
list.append(data)
cursor=cnx.cursor()
sql = “insert into data_test(uid,log_date,fr,is_login,url)values(%s,%s,%s,%s,%s)”
if i>5000:
cursor.executemany(sql,list)
cnx.commit()
print(“挿入”)
i=0
list.clear()
i=i+1
if i>0:
cursor.executemany(sql,list)
cnx.commit()
cnx.close()
f.close()
print(“ok”)
def listFiles(self):
d = os.listdir(“E:/data_startnews24/”)
return d

if __name__ == “__main__”:
readFile = ReadFile()
readFile.readLines()

「Python初心者」contextlibモジュールを利用する参考ソースコード

例1:
with open(“filename”) as f:
f.read()

例2
class closing(object):
def __init__(self, thing):
self.thing = thing
def __enter__(self):
return self.thing
def __exit__(self, *exc_info):
self.thing.close()