Python单词接龙小程序
偶然间阅读资料发现Linux发行版内置了英语词典,随手用Python写个小程序进行词语接龙
规则:用户给出第一个词,系统根据结尾随机给出一个相同开头的词,如此反复
用户词不得重复,单词表中也不含缩写符号的词
代码如下
#!/usr/bin/python3 from random import sample file = open(‘/usr/share/dict/words‘) word = [x[:-1] for x in file.readlines() if "‘" not in x] file.close() # [word.remove(x) for x in word if x[-1]==‘s‘ and x[:-1] in word] begin = False com = ‘‘ used = [] num = 0 while True: while True: usr = input(‘Your word =‘) if usr not in word: print(‘Word‘,usr,‘not found!‘) continue elif usr in used: print(‘You have used‘,usr,‘before!‘) continue else: break if begin and usr[0] != com[-1]: print(‘Must begin with‘,com[-1]) continue ans = [x for x in word if x[0]==usr[-1]] com, = sample(ans,1) num += 1 print(‘[Your turn %d‘%num, com) used.append(usr) begin = True
愉快的玩耍吧!实测s开头的特别多……
体验不佳可打开第7行注释过滤各类复数词,对应初始化时间也会随之增加。