之間的所有中間字母我需要拿出一個文件並洗牌每個單詞的中間字母,但我無法洗牌第一個和最後一個字母,而且我只能洗牌超過3個字符的單詞。我想我可以找出一種方法來打亂他們,如果我可以把每個單詞放在他們自己的單獨列表中,所有的字母都是分開的。任何幫助,將不勝感激。謝謝。接收文件並洗牌
Q
接收文件並洗牌
0
A
回答
3
text = "Take in a file and shuffle all the middle letters in between"
words = text.split()
def shuffle(word):
# get your word as a list
word = list(word)
# perform the shuffle operation
# return the list as a string
word = ''.join(word)
return word
for word in words:
if len(word) > 3:
print word[0] + ' ' + shuffle(word[1:-1]) + ' ' + word[-1]
else:
print word
有意不實施洗牌算法。
0
看看random.shuffle。它將一個列表對象洗牌,這似乎是你正在瞄準的目標。你可以做這樣的事情洗牌周圍
`
def scramble(word):
output = list(word[1:-1])
random.shuffle(output)
output.append(word[-1])
return word[0] + "".join(output)`
字母只記得導入隨機
+0
謝謝。 Random.shuffle非常有用=) – Albo 2012-01-06 01:44:16
0
#with open("words.txt",'w') as f:
# f.write("one two three four five\nsix seven eight nine")
def get_words(f):
for line in f:
for word in line.split():
yield word
import random
def shuffle_word(word):
if len(word)>3:
word=list(word)
middle=word[1:-1]
random.shuffle(middle)
word[1:-1]=middle
word="".join(word)
return word
with open("words.txt") as f:
#print list(get_words(f))
#['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
#print map(shuffle_word,get_words(f))
#['one', 'two', 'trhee', 'four', 'fvie', 'six', 'sveen', 'eihgt', 'nnie']
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(" ".join(map(shuffle_word,get_words(f))))
fname=tmp.name
import shutil
shutil.move(fname,"words.txt")
+0
我認爲你不想保留換行符。如果你這樣做了,那麼簡單地用get_words() – 2012-01-06 01:51:15
相關問題
- 1. 洗牌.txt文件隨機
- 2. 閱讀文本文件和洗牌
- 3. 洗牌回收數據的算法
- 4. 收到錯誤:洗牌(...)在angularJS
- 5. 洗牌算法:晚餐部門洗牌
- 6. 洗牌一副牌?
- 7. 在mapreduce中洗牌大數據文件
- 8. 在分隔的文件洗牌列
- 9. 洗牌DefaultListModel
- 10. java:卡洗牌,
- 11. 如何洗牌
- 12. 火花洗牌
- 13. 洗牌一套
- 14. SwiftyJSON洗牌
- 15. 洗牌註冊
- 16. 測試卡牌洗牌機
- 17. PHP陣列洗牌HTML鏈接
- 18. 更新從接入洗牌行
- 19. Javascript洗牌字母
- 20. 如何洗牌對
- 21. Select2洗牌選項
- 22. 洗牌陣列javascript
- 23. masonry.js不會洗牌
- 24. 陣列洗牌java
- 25. 洗牌在Objective-C
- 26. 洗牌類實例
- 27. NSArray無法洗牌
- 28. 洗牌Python的list
- 29. 優化洗牌ArrayList
- 30. 洗牌鏈表棧
那麼你嘗試過什麼呢?你究竟在哪裏遇到問題?分解它,嘗試編碼 - 因爲它沒有真正的問題需要回答。 – Yuushi 2012-01-06 01:06:37