Skip to content

Add solutions to 0005,0006 #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions renzongxian/0005/0005.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-12-08
# Python 3.4

"""

你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率(1136*640)的大小。

"""

from PIL import Image
import os
import sys


def resize_image(image):
im = Image.open(image)
weight, height = im.size
if weight > 1136 or height > 640:
dw = weight / 1136
dh = height / 640
ds = max(dw, dh)
new_weight = int(weight / ds)
new_height = int(height / ds)
im = im.resize((new_weight, new_height))
print("Succeed to resize the image %s to %s*%s " % (image, new_weight, new_height))
im.save(image)
else:
print("The image %s doesn't need to be resized." % image)


if __name__ == "__main__":
if len(sys.argv) <= 1:
print("Need at least 1 parameter. Try to execute 'python 0005.py $dir_path'")
else:
for dir_path in sys.argv[1:]:
for image_name in os.listdir(dir_path):
image_path = os.path.join(dir_path, image_name)
resize_image(image_path)
45 changes: 45 additions & 0 deletions renzongxian/0006/0006.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-12-08
# Python 3.4

"""

第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。

"""

import os
import sys
import re


def important_word(target_file):
file_object = open(target_file, 'r')
file_content = file_object.read()

# Split the string
p = re.compile(r'[\W\d]*')
word_list = p.split(file_content)

word_dict = {}
for word in word_list:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
sort = sorted(word_dict.items(), key=lambda e: e[1], reverse=True)

print("The most word in '%s' is '%s', it appears %s times" % (target_file, sort[0][0], sort[0][1]))
print("The second most word in '%s' is '%s', it appears %s times" % (target_file, sort[1][0], sort[1][1]))
file_object.close()


if __name__ == "__main__":
if len(sys.argv) <= 1:
print("Need at least 1 parameter. Try to execute 'python 0006.py $dir_path'")
else:
for dir_path in sys.argv[1:]:
for file_name in os.listdir(dir_path):
file_path = os.path.join(dir_path, file_name)
important_word(file_path)