2016-05-01 9 views
0

私はPythonを使い始めました。これは私自身の最初のプログラムです。私は達成するために私のプログラムを意図していることを(私の能力の最大限に)説明しました。私は新しいので、構文/パフォーマンスの改善提案があれば感謝します。バルクはPythonを使ってディレクトリにファイル名を追加します

''' 
     Search through a target movies directory and filter movie titles 
     to search IMDb for movie ratings. After fetching, append ratings 
     to corresponding movie files/folders in the directory. 

     File names are in one of the following formats: 
     1. P.S. I Love You.mkv 
     2. P.S. I Love You (2010).mp4 
     3. P.S. I Love You (2010) [1080p].avi 

     Ideally, this program fetched the movie ratings and adds it to 
     the end of the file name (just before the extension). The query, 
     in this case, would be http://www.omdbapi.com/?t=P.S.+I+Love+You 

     Ideally, the file in the directory would be renamed to one of the 
     following: 
     1. P.S. I Love You (7.1).mkv 
     2. P.S. I Love You (2010) (7.1).mp4 
     3. P.S. I Love You (2010) [1080p] (7.1).avi 
    ''' 

    import os, json, urllib.request, re 

    # Query related constants 
    base_uri = "http://www.omdbapi.com/?" 
    query_title = "t=" 

    basepath = "E:/Movies" 

    # Fetch movie rating from omdbapi.com 
    # Example JSON response: http://www.omdbapi.com/?t=insurgent 
    def getRating(movie_title): 
     # json_response = urllib.urlopen(base_uri + query_title + movie_title) 
     # movie_data = json.loads(json_response.read()) 
     with urllib.request.urlopen(base_uri + query_title + movie_title) as url: 
      movie_data = url.read() 
     return movie_data['imdbRating'] 

    # Checks if parameter file name already has a rating. 
    # Movie ratings are 
    def hasRating(filename): 
     pattern = re.compile('\([0-9].[0-9]\)') 
     if pattern.search(filename) is not None: 
      return True 
     return False 

    # Get the movie title by stripping out excess information such as the 
    # year released or video definition 
    def getMovieTitle(filename): 
     if '(' not in filename is False: 
      return filename.split('(')[0] 
     elif'[' not in filename is False: 
      return filename.split('[')[0] 
     return os.path.splitext(basepath + filename)[:-1] 


    def main(): 
     for file in os.listdir(basepath): 
      if hasRating(file) is False: 
       movie_title = getMovieTitle(file) 
       file_ext = os.path.splitext(basepath + file)[-1:] 
       movie_rating = getRating(movie_title) 
       formatted_rating = ' (' + movie_rating + ')' 
       file_no_ext = os.path.splitext(basepath + file)[:-1] 

       os.rename(file, file_no_ext + ' ' + formatted_rating + file_ext) 

    if __name__ == '__main__': 
     main() 

私はこれまでのところ、私ができることはすべてを修正しようとしましたが、私は同じエラーに到着保つ:

Traceback (most recent call last): 
    File "renamer.py", line 65, in <module> 
    main() 
    File "renamer.py", line 58, in main 
    movie_rating = getRating(movie_title) 
    File "renamer.py", line 33, in getRating 
    with urllib.request.urlopen(base_uri + query_title + movie_title) as url: 
TypeError: Can't convert 'tuple' object to str implicitly 

私はそれが起こる理由TypeErrorは、何であるか知らせてください、そしてどのようなIそれを修正することができます。

Javaから来ているPythonのシンプルさは圧倒的ですが、同時に爽快です。とにかく、あなたの入力のために事前に感謝!

答えて

2

getMovieTitleは、ifの条件が真である場合、タプルを返します。だからmovie_titleはタプルであり、getRatingはそれを処理できません(文字列とタプルの「追加」はTypeError例外になります)。

リストの最後の要素を返すのは、です。あなたはos.path.splitextから使用することを期待することは最初の部分であるので、

return os.path.splitext(basepath + filename)[0] 

第二に、この行のインデックスは0

return os.path.splitext(basepath + filename)[:-1] 

ターンを使用し、あなたはurl.read()を読んだ後の文字列であるmovie_dataにアクセスしていますmovie_data['imdbRating']。あなたはおそらくしたいこと(JSONである)の結果をデコードし、その要素にアクセスすることです:

with urllib.request.urlopen(base_uri + query_title + movie_title) as url: 
    movie_data = json.loads(url.read())['imdbRating'] 

これがある限り働く「imdbRating」ルート辞書のキーです。

+0

この文では、拡張子を付けずにファイル名を返そうとしています。したがって、ファイル名の最後の部分(拡張子)を除くすべてを返します。 – Vishal

+0

'' '.join(os.path.splitext(basepath + filename)[: - 1]) 'を使用した場合、タプルの値を空の文字列で結合します。 '( 'a'、 'b'、 'c')'は '' abc ''を取得します。 –

+0

'splitext'は '(root、ext)'という2つの値を持つタプルを与えます。インデックス0を使用して期待どおりに動作させる –

関連する問題