顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2018年4月15日 星期日

pip的相關指令用法

1: 更新pip
     python -m pip install -U pip

2: 更新所有的package
    $ pip install pip-review
    $ pip-review --local --interactive

2018年4月7日 星期六

('Connection aborted.', ConnectionResetError(10054, '遠端主機已強制關閉一個現存的連線。', None, 10054, None))

將原先的http, 重新賦予值就ok了.

retries = urllib3.Retry(connect=5, read=2, redirect=5)
http = urllib3.PoolManager(retries=retries)

try:
     pass
except:
     http = urllib3.PoolManager(retries=retries)

2018年3月11日 星期日

eclipse console 錯誤

UnicodeEncodeError: 'cp950' codec can't encode character '\xa0' in position 0: illegal multibyte sequence

這是因為所使用的eclipse 的console編碼問題, 將eclipse設定值改為utf-8就ok了

Run->Run Configurations->Common->Encoding->choise UTF-8->Apply

改為utf-8 就解決了.

2017年11月5日 星期日

python dict

haha = {'money':50000, 'stock':{'0050':4, '0052':30}, 'sell':{'0011','0022'}} haha['stock']['0053'] = 44 haha['stock']['0050'] = 14 haha['test']= dict() haha['test']['insert'] = 1 del haha['stock']['0050'] print(haha) 輸出 {'money': 50000, 'stock': {'0052': 30, '0053': 44}, 'sell': {'0022', '0011'}, 'test': {'insert': 1}}

2017年9月3日 星期日

2017年9月2日 星期六

python 更新

python -m pip install --upgrade pip

python HTMLParser

# -*- coding: utf-8 -*-

from html.parser import HTMLParser
import logging
import urllib3
import re

class MyHTMLParser(HTMLParser):
    test = []
    startFlag = False
    def handle_data(self, data):
        new_data = data.replace(' ','').replace(',','')
        
        ret = re.match(r'^\d{4}$', new_data) #只需要4位數的股票,權證之類不用.
        
        if ret != None and self.startFlag == False:
            self.startFlag = True
            self.test.append(new_data)  
        elif len(self.test) < 10 and self.startFlag == True:
            self.test.append(new_data)
        elif len(self.test) == 10:
            for w in self.test:
                print(w, end ='*')
            print('  ')
            print('===============')
            self.startFlag = False
            self.test[:] = []
            

def main():
    http = urllib3.PoolManager()
    r = http.request('GET', 'http://mops.twse.com.tw/nas/t21/sii/t21sc03_106_6_0.html')
    
    FORMAT = '%(message)s'
    logging.basicConfig(level=logging.DEBUG, format=FORMAT, filename='system.log')
    
    #logging.debug(r.data.decode('big5', 'ignore'))
    #print(r.data)
    parser = MyHTMLParser()
    parser.feed(r.data.decode('big5', 'ignore'))
    #gg = '              5,106,247'
    #print(gg.replace(' ', '').replace(',', ''))

if __name__ == '__main__':
    main()


效果:
1213*大飲*46321*49849*70686*-7.07*-34.46*295094*312894*-5.68*

2017年8月26日 星期六

python mongodb add item into object

{
    "_id" : ObjectId("59a0ee13a7715608c4877229"),
    "id" : "0050",
    "name" : "元大台灣50",
    "date" : [
        {
            "time" : "20160801",
            "overShares" : "10,407,371",
            "tradingVol" : "1,682",
            "overMoney" : "720,963,537",
            "openPrice" : "68.80",
            "dayHightPrice" : "69.45",
            "dayLowPrice" : "68.80",
            "closePrice" : "69.30",
            "per" : "0.00"
        }
    ]
}

{
    "_id" : ObjectId("59a18587a7715626ec3e6d43"),
    "id" : "0050",
    "name" : "元大台灣50",
    "date" : [
        {
            "time" : "20160801",
            "overShares" : "10,407,371",
            "tradingVol" : "1,682",
            "overMoney" : "720,963,537",
            "openPrice" : "68.80",
            "dayHightPrice" : "69.45",
            "dayLowPrice" : "68.80",
            "closePrice" : "69.30",
            "per" : "0.00",
            "sellStockShortCount" : "148",
            "sellStockShortMoney" : "10256600",
            "stockLendCount" : "0",
            "stockLendMoney" : "0"
        }
    ]
}

code:

collection = self.db[self.collectTitle]
collection.update({'id':stId,'date.time':saveTimeFormat}, {'$set':{'date.$.sellStockShortCount':stSellStockShortCount,
                                                                   'date.$.sellStockShortMoney':stSellStockShortMoney,
                                                                   'date.$.stockLendCount':stStockLendCount,
                                                                   'date.$.stockLendMoney':stStockLendMoney}})

2017年8月19日 星期六

python logging

# -*- coding: utf-8 -*-

import logging

from wmm.data.tw_stock import TwStock

def initLogging():
    FORMAT = '[%(asctime)s][%(levelname)s] %(message)s'
    logging.basicConfig(level=logging.DEBUG, format=FORMAT, filename='log/system.log')
     
def main():
    initLogging()

    test = TwStock()
    test.updateDB()

if __name__ == '__main__':
    main()


有一些參數參考
https://docs.python.org/3/library/logging.html

2017年7月28日 星期五

python import 不同資料夾的class

在__main__.py想要import在tw_stock.py所寫的class

只需要做

from wmm.data.tw_stock import TwStock

這樣就可以使用到TwStock這個class了.

2017年2月23日 星期四

python 執行方式

1: python mp3.py

2: 在mp3.py 第一行
    #!/usr/bin/python3   指定python的位置
    或者
    #!/usr/bin/env  python   這個不一定是你想要的python 解釋器, 所以也可能遇到python2 ,         python3 語法上解釋的問題
    然後再# ./mp3.py執行它

2014年12月9日 星期二

python 常用方法,函數,筆記

1:os.path.isfile  確認檔案是否存在

2:
import os
filename = os.environ.get(''PYTHONSTARTUP)
if filename and os.path.isfile(filename):
    exec(open(filename).read());

3:
print(b,end=",")
1,1,2,3,5,8,13,21,34,

4:
x=int(input("\nplease enter a number:"))
if x < 10:
   print("x < 10")
elif x < 20:
   print("x < 20")
else:
   print("haha")

5:print(n,'equals',x,'x',n//x)
4 equals 2 * 2


6:
def fib(n):
    a,b = 0 ,1
    while b < n:  
       print("haha=",b)
       a,b = b,a+b
   
fib(100)

7:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError('uncooperative user')
        print(complaint)          
       
ask_ok("Do you really want to quit?")


8:
def printdoc():
    """
    Doc start
   
    Doc medion
   
    Doc botton
    """
    pass

print(printdoc.__doc__)

9: 除法不要小數點
5 // 2
要小數點
5 / 2

階乘
5 ** 2

10:
def max(m, n):
    return m if m > n else n

print(max(10, 3))  # 顯示 10

類似c 三位元運算子,  val  = x ? y : z ;

11:列表推導
squares = [x**2 for x in range(10)]

2014年12月6日 星期六

python 編譯環境選擇

Notepad++
1:
勾選NppExec安裝

2: 按下F6
C
Command(s)
加入c:\Python34\python.exe -u "$(FULL_CURRENT_PATH)"
我取名haha_python 

3:當修改完python時 , 存檔 , 按下F6 ,再按ok . 此時可以看到執行結果


PyCharm
1: 有社群版可以用
2:函數自動提示