from collections import Counter
import re
f = open('罗密欧与朱丽叶(英文版)莎士比亚.txt',"r")
txt = f.read()
txt = re.compile(r'W+').split(txt.lower())
# 统计所有词出现的次数
splits = Counter(name for name in txt)
# 输出出现次数排名前20的单词
top_n = sorted(splits.items(), key=lambda pair:pair[0], reverse=False)
top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True)
for i in range
print(top_n[:20])
[('and', 720), ('the', 681), ('i', 658), ('to', 577), ('a', 470), ('of', 401), ('my', 361), ('that', 355), ('is', 349), ('in', 320), ('you', 295), ('s', 293), ('thou', 278), ('me', 265), ('not', 260), ('with', 255), ('d', 236), ('it', 228), ('this', 226), ('for', 225)]
# 输出romeo和juliet出现的次数
print("罗密欧出现了: ",splits["romeo"]," 次")
print("朱丽叶出现了: ",splits["juliet"]," 次")
罗密欧出现了: 156 次
朱丽叶出现了: 66 次
1.计算1+2+...+10
import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
value = tf.Variable(0,name="value")
sum0 = tf.Variable(0,name="sum")
one = tf.constant(1)
add0 = tf.add(sum0,value) #sum加上这个数
update_value_sum = tf.assign(sum0,add0) #将sum赋值
new_value = tf.add(value,one) #value值+1
update_value = tf.assign(value,new_value) #将value赋值
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_value)
sess.run(update_value_sum)
print("1+2+...+10 =",sess.run(sum0))
1+2+...+10 = 55
2.计算1+2+...+n
(1)对输入的n使用占位符
import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
a = int(input("请输入一个整数:"))
value = tf.Variable(0,name="value")
sum0 = tf.Variable(0,name="sum")
one = tf.constant(1)
add0 = tf.add(sum0,value)
update_value_sum = tf.assign(sum0,add0)
new_value = tf.add(value,one)
update_value = tf.assign(value,new_value)
n = tf.placeholder(tf.int32)
toInt = tf.add(0,n)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(sess.run(toInt,feed_dict={n:a})):
sess.run(update_value)
sess.run(update_value_sum)
print("1+2+...+ %d = %d" % (a,sess.run(sum0)))
请输入一个整数:100
1+2+...+ 100 = 5050
(2)对中间变量使用占位符
import tensorflow as tf
n = int(input("请输入一个整数:"))
value = tf.Variable(0,name="value")
one = tf.constant(1)
temp = tf.placeholder(tf.int32, name="temp")
result = tf.Variable(0,name="value")
new_value = tf.add(value,one)
update_value = tf.assign(value,new_value)
new_result = tf.add(result,temp)
update_result = tf.assign(result,new_result)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(n):
sum0 = sess.run(update_result, feed_dict={temp:sess.run(update_value)})
print("1+2+...+ %d = %d" % (n,sum0))
请输入一个整数:101
1+2+...+ 101 = 5151
3.模拟矩阵运算 [[1.0, 2.0], [3.0, 4.0]] + [[5, 6], [7, 8]] * 9 – 10E
import tensorflow as tf
a = tf.Variable([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)
b = tf.Variable([[5.0, 6.0], [7.0, 8.0]], dtype=tf.float32)
e = tf.eye(2) # 二阶单位阵
result = a+b*9-10*e
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("最终结果是:
",sess.run(result))
最终结果是:
[[36. 56.]
[66. 66.]]