[英]how to print only 1st argument in two arguments function?
我有一個 txt.file 和字符串輸入作為 arguments,給定字符串輸入我的 function 將從一組文件中打印相應的行/字符串。 文件每行一個單詞。
def angram(s1,s2):
st = set()
if sorted(s1) == sorted(s2):
st.add(s1)
return st
angram('my.txt', 'top')
expected output: {'pot'}
but output I get {'pot','top'}
我不希望在集合中輸入字符串。 我只想要文件中的 output 結果。 有什么辦法嗎??
您需要使用 Python 內置函數來讀取文件。 https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/
鑒於:
car
pto
pot
Output:
{'pot', 'pto'}
代碼:
def anagram(s1,s2):
st = set()
fh = open('my.txt')
target = sorted(s2)
while True:
line = fh.readline() # while there is line to read in the file
check = line.strip('\n') # some lines will include "\n" in index 0 - remove it
if sorted(check) == target:
st.add(check)
if not line:
break
fh.close()
st.remove(s2) # the user doesn't want the same word as the target (s2) to be included
return st
anagram('my.txt', 'top')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.